Java Code Examples for javax.security.auth.Subject
The following examples show how to use
javax.security.auth.Subject.
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: openjdk-jdk8u-backup Author: AdoptOpenJDK File: KrbCredSubKey.java License: GNU General Public License v2.0 | 9 votes |
public static void main(String[] args) throws Exception { // We don't care about clock difference new FileOutputStream("krb5.conf").write( "[libdefaults]\nclockskew=999999999".getBytes()); System.setProperty("java.security.krb5.conf", "krb5.conf"); Config.refresh(); Subject subj = new Subject(); KerberosPrincipal kp = new KerberosPrincipal(princ); KerberosKey kk = new KerberosKey( kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0); subj.getPrincipals().add(kp); subj.getPrivateCredentials().add(kk); Subject.doAs(subj, new PrivilegedExceptionAction() { public Object run() throws Exception { GSSManager man = GSSManager.getInstance(); GSSContext ctxt = man.createContext(man.createCredential( null, GSSCredential.INDEFINITE_LIFETIME, GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY)); return ctxt.acceptSecContext(token, 0, token.length); } }); }
Example #2
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: NestedActions.java License: GNU General Public License v2.0 | 6 votes |
@Override public Object run() { AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); System.out.println("principals = " + subject.getPrincipals()); try { Utils.writeFile(filename); new File(filename).delete(); throw new RuntimeException( "Test failed: no AccessControlException thrown"); } catch (AccessControlException ace) { System.out.println( "AccessControlException thrown as expected: " + ace.getMessage()); } ReadFromFileNegativeAction readFromFile = new ReadFromFileNegativeAction(filename); return Subject.doAs(subject, readFromFile); }
Example #3
Source Project: jdk8u_jdk Author: JetBrains File: NotificationAccessControllerTest.java License: GNU General Public License v2.0 | 6 votes |
@Override public void fetchNotification( String connectionId, ObjectName name, Notification notification, Subject subject) throws SecurityException { echo("fetchNotification:"); echo("\tconnectionId: " + connectionId); echo("\tname: " + name); echo("\tnotification: " + notification); echo("\tsubject: " + (subject == null ? null : subject.getPrincipals())); if (!throwException) if (name.getCanonicalName().equals("domain:name=2,type=NB") && subject != null && subject.getPrincipals().contains(new JMXPrincipal("role"))) throw new SecurityException(); }
Example #4
Source Project: ironjacamar Author: ironjacamar File: HelloWorldManagedConnectionFactory.java License: Eclipse Public License 1.0 | 6 votes |
/** * Returns a matched connection from the candidate set of connections. * * @param connectionSet Candidate connection set * @param subject Caller's security information * @param cxRequestInfo Additional resource adapter specific connection request information * @throws ResourceException generic exception * @return ManagedConnection if resource adapter finds an acceptable match otherwise null */ public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException { ManagedConnection result = null; Iterator it = connectionSet.iterator(); while (result == null && it.hasNext()) { ManagedConnection mc = (ManagedConnection)it.next(); if (mc instanceof HelloWorldManagedConnection) { HelloWorldManagedConnection hwmc = (HelloWorldManagedConnection)mc; result = hwmc; } } return result; }
Example #5
Source Project: knox Author: apache File: SwitchCaseIdentityAssertionFilterTest.java License: Apache License 2.0 | 6 votes |
@Test public void testNoGroups() throws Exception { FilterConfig config = EasyMock.createNiceMock( FilterConfig.class ); EasyMock.expect( config.getInitParameter( "principal.case" ) ).andReturn( "upper" ).anyTimes(); EasyMock.expect( config.getInitParameter( "group.principal.case" ) ).andReturn( "upper" ).anyTimes(); EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes(); ServletContext context = EasyMock.createNiceMock(ServletContext.class); EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes(); EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes(); EasyMock.replay( config ); EasyMock.replay( context ); SwitchCaseIdentityAssertionFilter filter = new SwitchCaseIdentityAssertionFilter(); Subject subject = new Subject(); subject.getPrincipals().add(new PrimaryPrincipal( "[email protected]" ) ); filter.init(config); String actual = filter.mapUserPrincipal(((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0]).getName()); String[] groups = filter.mapGroupPrincipals(actual, subject); assertThat( actual, is( "[email protected]" ) ); assertThat( groups, is( nullValue() ) ); }
Example #6
Source Project: jdk8u_jdk Author: JetBrains File: Implies.java License: GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { X500Principal duke = new X500Principal("CN=Duke"); // should not throw NullPointerException testImplies(duke, (Subject)null, false); Set<Principal> principals = new HashSet<>(); principals.add(duke); testImplies(duke, principals, true); X500Principal tux = new X500Principal("CN=Tux"); principals.add(tux); testImplies(duke, principals, true); principals.add(new KerberosPrincipal("[email protected]")); testImplies(duke, principals, true); principals.clear(); principals.add(tux); testImplies(duke, principals, false); System.out.println("test passed"); }
Example #7
Source Project: jdk8u-dev-jdk Author: frohoff File: Synch3.java License: GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { Subject subject = new Subject(); final Set principals = subject.getPrincipals(); principals.add(new X500Principal("CN=Alice")); new Thread() { { start(); } public void run() { X500Principal p = new X500Principal("CN=Bob"); while (!finished) { principals.add(p); principals.remove(p); } } }; for (int i = 0; i < 1000; i++) { subject.getPrincipals(X500Principal.class); } finished = true; }
Example #8
Source Project: lams Author: lamsfoundation File: SubjectActions.java License: GNU General Public License v2.0 | 6 votes |
static LoginContext createLoginContext(String securityDomain, Subject subject, CallbackHandler handler) throws LoginException { LoginContextAction action = new LoginContextAction(securityDomain, subject, handler); try { LoginContext lc = AccessController.doPrivileged(action); return lc; } catch(PrivilegedActionException e) { Exception ex = e.getException(); if( ex instanceof LoginException ) throw (LoginException) ex; else throw new LoginException(ex.getLocalizedMessage()); } }
Example #9
Source Project: ranger Author: apache File: KrbPasswordSaverLoginModule.java License: Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") @Override public void initialize(Subject subject, CallbackHandler callbackhandler, Map<String, ?> sharedMap, Map<String, ?> options) { this.sharedState = sharedMap; String userName = (options != null) ? (String)options.get(USERNAME_PARAM) : null; if (userName != null) { this.sharedState.put(USERNAME_PARAM,userName); } String password = (options != null) ? (String)options.get(PASSWORD_PARAM) : null; if (password != null) { this.sharedState.put(PASSWORD_PARAM,password.toCharArray()); } }
Example #10
Source Project: jdk8u_jdk Author: JetBrains File: NestedActions.java License: GNU General Public License v2.0 | 6 votes |
@Override public Object run() { AccessControlContext acc = AccessController.getContext(); Subject subject = Subject.getSubject(acc); System.out.println("principals = " + subject.getPrincipals()); try { Utils.writeFile(filename); new File(filename).delete(); throw new RuntimeException( "Test failed: no AccessControlException thrown"); } catch (AccessControlException ace) { System.out.println( "AccessControlException thrown as expected: " + ace.getMessage()); } ReadFromFileNegativeAction readFromFile = new ReadFromFileNegativeAction(filename); return Subject.doAs(subject, readFromFile); }
Example #11
Source Project: streamline Author: hortonworks File: StormRestAPIClient.java License: Apache License 2.0 | 6 votes |
private Map doGetRequest(String requestUrl) { try { LOG.debug("GET request to Storm cluster: " + requestUrl); return Subject.doAs(subject, new PrivilegedAction<Map>() { @Override public Map run() { return JsonClientUtil.getEntity(client.target(requestUrl), STORM_REST_API_MEDIA_TYPE, Map.class); } }); } catch (RuntimeException ex) { Throwable cause = ex.getCause(); // JsonClientUtil wraps exception, so need to compare if (cause instanceof javax.ws.rs.ProcessingException) { if (ex.getCause().getCause() instanceof IOException) { throw new StormNotReachableException("Exception while requesting " + requestUrl, ex); } } else if (cause instanceof WebApplicationException) { throw WrappedWebApplicationException.of((WebApplicationException)cause); } throw ex; } }
Example #12
Source Project: scheduling Author: ow2-proactive File: SelectionManagerTest.java License: GNU Affero General Public License v3.0 | 6 votes |
@Test public void selectWithDifferentPermissions() throws Exception { PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER.updateProperty("10"); System.out.println("PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER=" + PAResourceManagerProperties.RM_SELECTION_MAX_THREAD_NUMBER); System.setSecurityManager(securityManagerRejectingUser()); RMCore.topologyManager = mock(TopologyManager.class); RMCore rmCore = mock(RMCore.class); when(RMCore.topologyManager.getHandler(Matchers.<TopologyDescriptor> any())).thenReturn(selectAllTopology()); SelectionManager selectionManager = createSelectionManager(rmCore); ArrayList<RMNode> freeNodes = new ArrayList<>(); freeNodes.add(createMockedNode("admin")); freeNodes.add(createMockedNode("user")); when(rmCore.getFreeNodes()).thenReturn(freeNodes); Criteria criteria = new Criteria(2); criteria.setTopology(TopologyDescriptor.ARBITRARY); Subject subject = Subjects.create("admin"); NodeSet nodes = selectionManager.selectNodes(criteria, new Client(subject, false)); assertEquals(1, nodes.size()); }
Example #13
Source Project: jdk8u-jdk Author: frohoff File: NotificationAccessControllerTest.java License: GNU General Public License v2.0 | 6 votes |
@Override public void addNotificationListener( String connectionId, ObjectName name, Subject subject) throws SecurityException { echo("addNotificationListener:"); echo("\tconnectionId: " + connectionId); echo("\tname: " + name); echo("\tsubject: " + (subject == null ? null : subject.getPrincipals())); if (throwException) if (name.getCanonicalName().equals("domain:name=1,type=NB") && subject != null && subject.getPrincipals().contains(new JMXPrincipal("role"))) throw new SecurityException(); }
Example #14
Source Project: jdk8u-jdk Author: frohoff File: ConnectorBootstrap.java License: GNU General Public License v2.0 | 6 votes |
private void checkAccessFileEntries(Subject subject) { if (subject == null) { throw new SecurityException( "Access denied! No matching entries found in " + "the access file [" + accessFile + "] as the " + "authenticated Subject is null"); } final Set<Principal> principals = subject.getPrincipals(); for (Principal p1: principals) { if (properties.containsKey(p1.getName())) { return; } } final Set<String> principalsStr = new HashSet<>(); for (Principal p2: principals) { principalsStr.add(p2.getName()); } throw new SecurityException( "Access denied! No entries found in the access file [" + accessFile + "] for any of the authenticated identities " + principalsStr); }
Example #15
Source Project: openjdk-8 Author: bpupadhyaya File: SelfExpansion.java License: GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { Subject s = new Subject(); s.getPrincipals().add (new javax.security.auth.x500.X500Principal("CN=test")); s.getPrivateCredentials().add(new String("test")); try { Subject.doAsPrivileged(s, new PrivilegedAction() { public Object run() { java.util.Iterator i = Subject.getSubject (AccessController.getContext ()).getPrivateCredentials().iterator(); return i.next(); } }, null); System.out.println("Test succeeded"); } catch (Exception e) { System.out.println("Test failed"); e.printStackTrace(); throw e; } }
Example #16
Source Project: lams Author: lamsfoundation File: SemaphoreArrayListManagedConnectionPool.java License: GNU General Public License v2.0 | 6 votes |
/** * Create a connection event listener * * @param subject the subject * @param cri the connection request information * @return the new listener * @throws ResourceException for any error */ private ConnectionListener createConnectionEventListener(Subject subject, ConnectionRequestInfo cri) throws ResourceException { long start = pool.getInternalStatistics().isEnabled() ? System.currentTimeMillis() : 0L; ManagedConnection mc = mcf.createManagedConnection(subject, cri); if (pool.getInternalStatistics().isEnabled()) { pool.getInternalStatistics().deltaTotalCreationTime(System.currentTimeMillis() - start); pool.getInternalStatistics().deltaCreatedCount(); } try { return cm.createConnectionListener(mc, this); } catch (ResourceException re) { if (pool.getInternalStatistics().isEnabled()) pool.getInternalStatistics().deltaDestroyedCount(); mc.destroy(); throw re; } }
Example #17
Source Project: datacollector Author: streamsets File: SecurityUtil.java License: Apache License 2.0 | 6 votes |
public static <T> T doAs( Subject subject, PrivilegedExceptionAction<T> privilegedExceptionAction ) throws PrivilegedActionException { checkDoAsPermission(); if (privilegedExceptionAction == null) { throw new RuntimeException("No privileged exception action provided"); } // The bug this class patches only affects JDK 8 & 9. In later JDK not only the issue is fixed but // the code collides with this patch causing strange behavior due to concurrency issues/race conditions. // Apply only the patch for versions <9, use the JDK AccessController directly for 9+ versions. if (getJavaVersion() <= 9) { return AccessController.doPrivileged(privilegedExceptionAction, createContext(subject, AccessController.getContext())); } else { return AccessController.doPrivileged(privilegedExceptionAction, AccessController.getContext()); } }
Example #18
Source Project: jdk8u60 Author: chenghanpeng File: Context.java License: GNU General Public License v2.0 | 6 votes |
public Context impersonate(final String someone) throws Exception { try { GSSCredential creds = Subject.doAs(s, new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws Exception { GSSManager m = GSSManager.getInstance(); GSSName other = m.createName(someone, GSSName.NT_USER_NAME); if (Context.this.cred == null) { Context.this.cred = m.createCredential(GSSCredential.INITIATE_ONLY); } return ((ExtendedGSSCredential)Context.this.cred).impersonate(other); } }); Context out = new Context(); out.s = s; out.cred = creds; out.name = name + " as " + out.cred.getName().toString(); return out; } catch (PrivilegedActionException pae) { throw pae.getException(); } }
Example #19
Source Project: steady Author: eclipse File: AbstractUsernameTokenAuthenticatingInterceptor.java License: Apache License 2.0 | 6 votes |
@Override public void handleMessage(SoapMessage msg) throws Fault { SecurityToken token = msg.get(SecurityToken.class); SecurityContext context = msg.get(SecurityContext.class); if (token == null || context == null || context.getUserPrincipal() == null) { super.handleMessage(msg); return; } UsernameToken ut = (UsernameToken)token; Subject subject = createSubject(ut.getName(), ut.getPassword(), ut.isHashed(), ut.getNonce(), ut.getCreatedTime()); SecurityContext sc = doCreateSecurityContext(context.getUserPrincipal(), subject); msg.put(SecurityContext.class, sc); }
Example #20
Source Project: jdk8u-jdk Author: frohoff File: RMIConnectionImpl.java License: GNU General Public License v2.0 | 5 votes |
public void removeNotificationListeners(ObjectName name, Integer[] listenerIDs, Subject delegationSubject) throws InstanceNotFoundException, ListenerNotFoundException, IOException { if (name == null || listenerIDs == null) throw new IllegalArgumentException("Illegal null parameter"); for (int i = 0; i < listenerIDs.length; i++) { if (listenerIDs[i] == null) throw new IllegalArgumentException("Null listener ID"); } try { final Object params[] = new Object[] { name, listenerIDs }; if (logger.debugOn()) logger.debug("removeNotificationListener"+ "(ObjectName,Integer[])", "connectionId=" + connectionId +", name=" + name +", listenerIDs=" + objects(listenerIDs)); doPrivilegedOperation( REMOVE_NOTIFICATION_LISTENER, params, delegationSubject); } catch (PrivilegedActionException pe) { Exception e = extractException(pe); if (e instanceof InstanceNotFoundException) throw (InstanceNotFoundException) e; if (e instanceof ListenerNotFoundException) throw (ListenerNotFoundException) e; if (e instanceof IOException) throw (IOException) e; throw newIOException("Got unexpected server exception: " + e, e); } }
Example #21
Source Project: qpid-broker-j Author: apache File: OAuth2PreemptiveAuthenticatorTest.java License: Apache License 2.0 | 5 votes |
@Test public void testAttemptAuthenticationInvalidToken() throws Exception { HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getServerName()).thenReturn("localhost"); when(mockRequest.getHeader("Authorization")).thenReturn("Bearer " + TEST_INVALID_ACCESS_TOKEN); Subject subject = _authenticator.attemptAuthentication(mockRequest, _mockConfiguration); assertNull("Authenticator did not fail with invalid access token", subject); }
Example #22
Source Project: qpid-broker-j Author: apache File: TaskExecutorTest.java License: Apache License 2.0 | 5 votes |
@Test public void testSubmitAndWaitInAuthorizedContextWithNullSubject() { _executor.start(); Object result = Subject.doAs(null, new PrivilegedAction<Object>() { @Override public Object run() { return _executor.run(new SubjectRetriever()); } }); assertEquals("Unexpected subject", null, result); }
Example #23
Source Project: openjdk-jdk8u Author: AdoptOpenJDK File: NestedActions.java License: GNU General Public License v2.0 | 5 votes |
public static void main(String args[]) { Subject subject = new Subject(); subject.getPrincipals().add(new X500Principal("CN=Duke")); WriteToFileAction writeToFile = new WriteToFileAction(NestedActions.file); Subject.doAs(subject, writeToFile); }
Example #24
Source Project: jdk8u60 Author: chenghanpeng File: NotificationAccessControllerTest.java License: GNU General Public License v2.0 | 5 votes |
@Override public Subject authenticate(Object credentials) { String role = ((String[]) credentials)[0]; echo("\nCreate principal with name = " + role); return new Subject(true, Collections.singleton(new JMXPrincipal(role)), Collections.EMPTY_SET, Collections.EMPTY_SET); }
Example #25
Source Project: jdk8u60 Author: chenghanpeng File: NotificationEmissionTest.java License: GNU General Public License v2.0 | 5 votes |
public Subject authenticate(Object credentials) { String role = ((String[]) credentials)[0]; echo("Create principal with name = " + role); return new Subject(true, Collections.singleton(new JMXPrincipal(role)), Collections.EMPTY_SET, Collections.EMPTY_SET); }
Example #26
Source Project: jdk8u-jdk Author: frohoff File: SubjectComber.java License: GNU General Public License v2.0 | 5 votes |
@SuppressWarnings("unchecked") // findAux returns List<T> if !oneOnly. static <T> List<T> findMany(Subject subject, String serverPrincipal, String clientPrincipal, Class<T> credClass) { return (List<T>)findAux(subject, serverPrincipal, clientPrincipal, credClass, false); }
Example #27
Source Project: pxf Author: greenplum-db File: PxfUserGroupInformation.java License: Apache License 2.0 | 5 votes |
static private void fixKerberosTicketOrder(Subject subject) { Set<Object> creds = subject.getPrivateCredentials(); synchronized (creds) { for (Iterator<Object> iter = creds.iterator(); iter.hasNext(); ) { Object cred = iter.next(); if (cred instanceof KerberosTicket) { KerberosTicket ticket = (KerberosTicket) cred; if (ticket.isDestroyed() || ticket.getServer() == null) { LOG.debug("Ticket is already destroyed, remove it."); iter.remove(); } else if (!ticket.getServer().getName().startsWith("krbtgt")) { LOG.debug("The first kerberos ticket is not TGT(the server principal is {}), remove and destroy it.", ticket.getServer()); iter.remove(); try { ticket.destroy(); } catch (DestroyFailedException e) { LOG.warn("destroy ticket failed", e); } } else { return; } } } } LOG.warn("Warning, no kerberos tickets found while attempting to renew ticket"); }
Example #28
Source Project: ranger Author: apache File: PrestoClient.java License: Apache License 2.0 | 5 votes |
private void init() throws Exception { Subject.doAs(getLoginSubject(), new PrivilegedAction<Void>() { public Void run() { initConnection(); return null; } }); }
Example #29
Source Project: jdk8u-jdk Author: lambdalab-mirror File: Context.java License: GNU General Public License v2.0 | 5 votes |
/** * Does something using the Subject inside * @param action the action * @param in the input byte * @return the output byte * @throws java.lang.Exception */ public byte[] doAs(final Action action, final byte[] in) throws Exception { try { return Subject.doAs(s, new PrivilegedExceptionAction<byte[]>() { @Override public byte[] run() throws Exception { return action.run(Context.this, in); } }); } catch (PrivilegedActionException pae) { throw pae.getException(); } }
Example #30
Source Project: keycloak Author: keycloak File: KerberosUsernamePasswordAuthenticator.java License: Apache License 2.0 | 5 votes |
/** * Returns true if user was successfully authenticated against Kerberos * * @param username username without Kerberos realm attached * @param password kerberos password * @return true if user was successfully authenticated */ public Subject authenticateSubject(String username, String password) throws LoginException { String principal = getKerberosPrincipal(username); logger.debug("Validating password of principal: " + principal); loginContext = new LoginContext("does-not-matter", null, createJaasCallbackHandler(principal, password), createJaasConfiguration()); loginContext.login(); logger.debug("Principal " + principal + " authenticated succesfully"); return loginContext.getSubject(); }