List of usage examples for javax.security.auth Subject getPrincipals
public Set<Principal> getPrincipals()
From source file:com.zimbra.cs.security.sasl.GssAuthenticator.java
private Subject getSubject(Krb5Keytab keytab, KerberosPrincipal kp) throws IOException { List<KerberosKey> keys = keytab.getKeys(kp); if (keys == null) { getLog().warn("Key not found in keystore for service principal '" + kp + "'"); return null; }/* www.j av a2 s.c om*/ Subject subject = new Subject(); subject.getPrincipals().add(kp); subject.getPrivateCredentials().addAll(keys); return subject; }
From source file:org.apache.ws.security.spnego.SpnegoTokenContext.java
/** * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this * BinarySecurityToken.// w ww . j a v a 2s . c o m * @param jaasLoginModuleName the JAAS Login Module name to use * @param callbackHandler a CallbackHandler instance to retrieve a password (optional) * @param serviceName the desired Kerberized service * @throws WSSecurityException */ public void retrieveServiceTicket(String jaasLoginModuleName, CallbackHandler callbackHandler, String serviceName) throws WSSecurityException { // Get a TGT from the KDC using JAAS LoginContext loginContext = null; try { if (callbackHandler == null) { loginContext = new LoginContext(jaasLoginModuleName); } else { loginContext = new LoginContext(jaasLoginModuleName, callbackHandler); } loginContext.login(); } catch (LoginException ex) { if (LOG.isDebugEnabled()) { LOG.debug(ex.getMessage(), ex); } throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError", new Object[] { ex.getMessage() }, ex); } if (LOG.isDebugEnabled()) { LOG.debug("Successfully authenticated to the TGT"); } Subject clientSubject = loginContext.getSubject(); Set<Principal> clientPrincipals = clientSubject.getPrincipals(); if (clientPrincipals.isEmpty()) { throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosLoginError", new Object[] { "No Client principals found after login" }); } // Get the service ticket clientAction.setServiceName(serviceName); clientAction.setMutualAuth(mutualAuth); token = (byte[]) Subject.doAs(clientSubject, clientAction); if (token == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError"); } secContext = clientAction.getContext(); if (LOG.isDebugEnabled()) { LOG.debug("Successfully retrieved a service ticket"); } }
From source file:org.apache.karaf.jaas.modules.ldap.LdapCacheTest.java
@Test public void testAdminLogin() throws Exception { Properties options = ldapLoginModuleOptions(); LDAPLoginModule module = new LDAPLoginModule(); CallbackHandler cb = new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (Callback cb : callbacks) { if (cb instanceof NameCallback) { ((NameCallback) cb).setName("admin"); } else if (cb instanceof PasswordCallback) { ((PasswordCallback) cb).setPassword("admin123".toCharArray()); }/*w w w.j a v a 2s. c o m*/ } } }; Subject subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals(2, subject.getPrincipals().size()); boolean foundUser = false; boolean foundRole = false; for (Principal pr : subject.getPrincipals()) { if (pr instanceof UserPrincipal) { assertEquals("admin", pr.getName()); foundUser = true; } else if (pr instanceof RolePrincipal) { assertEquals("admin", pr.getName()); foundRole = true; } } assertTrue(foundUser); assertTrue(foundRole); assertTrue(module.logout()); assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size()); DirContext context = new LDAPCache(new LDAPOptions(options)).open(); // Make "admin" user a member of a new "another" group // dn: cn=admin,ou=groups,dc=example,dc=com // objectClass: top // objectClass: groupOfNames // cn: admin // member: cn=admin,ou=people,dc=example,dc=com Attributes entry = new BasicAttributes(); entry.put(new BasicAttribute("cn", "another")); Attribute oc = new BasicAttribute("objectClass"); oc.add("top"); oc.add("groupOfNames"); entry.put(oc); Attribute mb = new BasicAttribute("member"); mb.add("cn=admin,ou=people,dc=example,dc=com"); entry.put(mb); context.createSubcontext("cn=another,ou=groups,dc=example,dc=com", entry); Thread.sleep(100); module = new LDAPLoginModule(); subject = new Subject(); module.initialize(subject, cb, null, options); assertEquals("Precondition", 0, subject.getPrincipals().size()); assertTrue(module.login()); assertTrue(module.commit()); assertEquals("Postcondition", 3, subject.getPrincipals().size()); }
From source file:org.wso2.carbon.identity.oauth2.token.handlers.grant.iwa.ntlm.NTLMAuthenticationGrantHandler.java
@Override public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { if (!super.validateGrant(tokReqMsgCtx)) { return false; }/*from w w w. j ava 2s .c om*/ NegotiateSecurityFilter filter; filter = new NegotiateSecurityFilter(); filter.setAuth(new WindowsAuthProviderImpl()); try { filter.init(null); } catch (ServletException e) { log.error("Error while initializing Negotiate Security Filter", e); throw new IdentityOAuth2Exception("Error while initializing Negotiate Security Filter", e); } String token = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getWindowsToken(); boolean authenticated; IWindowsCredentialsHandle clientCredentials; WindowsSecurityContextImpl clientContext; filter.setRoleFormat("both"); if (token != null) { // Logging the windows authentication object if (log.isDebugEnabled()) { log.debug("Received NTLM Token : " + tokReqMsgCtx.getOauth2AccessTokenReqDTO().getWindowsToken()); } // client credentials handle clientCredentials = WindowsCredentialsHandleImpl.getCurrent(securityPackage); clientCredentials.initialize(); // initial client security context clientContext = new WindowsSecurityContextImpl(); clientContext.setPrincipalName(WindowsAccountImpl.getCurrentUsername()); clientContext.setCredentialsHandle(clientCredentials.getHandle()); clientContext.setSecurityPackage(securityPackage); clientContext.initialize(null, null, WindowsAccountImpl.getCurrentUsername()); SimpleHttpRequest request = new SimpleHttpRequest(); SimpleFilterChain filterChain = new SimpleFilterChain(); while (true) { try { request.addHeader("Authorization", securityPackage + " " + token); SimpleHttpResponse response = new SimpleHttpResponse(); try { filter.doFilter(request, response, filterChain); } catch (IOException e) { log.error("You have been given wrong inputs to negotiate filter", e); throw new IdentityOAuth2Exception("Error while processing negotiate the filter.", e); } Subject subject = (Subject) request.getSession().getAttribute("javax.security.auth.subject"); authenticated = (subject != null && subject.getPrincipals().size() > 0); if (authenticated) { if (log.isDebugEnabled()) { log.debug("NTLM token is authenticated"); } String resourceOwnerUserNameWithDomain = WindowsAccountImpl.getCurrentUsername(); String resourceOwnerUserName = resourceOwnerUserNameWithDomain.split("\\\\")[1]; tokReqMsgCtx.setAuthorizedUser(OAuth2Util.getUserFromUserName(resourceOwnerUserName)); break; } String continueToken = response.getHeader("WWW-Authenticate") .substring(securityPackage.length() + 1); byte[] continueTokenBytes = Base64.decode(continueToken); Sspi.SecBufferDesc continueTokenBuffer = new Sspi.SecBufferDesc(Sspi.SECBUFFER_TOKEN, continueTokenBytes); clientContext.initialize(clientContext.getHandle(), continueTokenBuffer, "localhost"); token = Base64.encode(clientContext.getToken()); } catch (Exception e) { log.error("Error while validating the NTLM authentication grant", e); throw new IdentityOAuth2Exception("Error while validating the NTLM authentication grant", e); } } } else { if (log.isDebugEnabled()) { log.debug("NTLM token is null"); } throw new IdentityOAuth2Exception("NTLM token is null"); } return authenticated; }
From source file:com.salesmanager.core.module.impl.application.logon.CustomerJAASLogonImpl.java
private boolean isValidLogin(HttpServletRequest req, String username, String password, int merchantId) { LoginContext context = null;//from w w w . ja v a2s . c om try { // 1) using jaas.conf // context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME,new // CustomerLoginCallBackHandler(username,password)); // 2) programaticaly created jaas.conf equivalent SalesManagerJAASConfiguration jaasc = new SalesManagerJAASConfiguration( "com.salesmanager.core.module.impl.application.logon.JAASSecurityCustomerLoginModule"); context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME, null, new CustomerLoginCallBackHandler(username, password, merchantId), jaasc); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Unable to Create Login Context, configuration file may be missing", e); /** * needs a jaas.conf file in the startup script Logon { * com.salesmanager.core.module.impl.application.logon. * JAASSecurityCustomerLoginModule required; }; and this parameter * -Djava.security.auth.login.config=jaas.conf */ } if (context != null) { try { context.login(); Subject s = context.getSubject(); if (s != null) { Set principals = s.getPrincipals(); } // Create a principal UserPrincipal principal = new UserPrincipal(username); HttpSession session = req.getSession(); session.setAttribute("PRINCIPAL", principal); session.setAttribute("LOGINCONTEXT", context); return true; } catch (LoginException e) { e.printStackTrace(); return false; } } return false; }
From source file:de.juwimm.cms.test.hibernate.HbmTestImpl.java
public void loginUser(String username, String password) { Principal p = null;//from w w w. ja va 2 s. c om if (loginContext == null) { SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler(username, password); try { loginContext = new LoginContext("juwimm-cms-security-domain", simpleCallbackHandler); loginContext.login(); Subject s = loginContext.getSubject(); Iterator it = s.getPrincipals().iterator(); if (!s.getPrincipals().isEmpty()) { while (it.hasNext()) { p = (Principal) it.next(); if (!p.getName().equalsIgnoreCase(SYSTEM_USER)) { org.andromda.spring.PrincipalStore.set(p); break; } } } } catch (LoginException e) { if (log.isErrorEnabled()) { log.error("Could not login: " + e.getMessage(), e); } } } }
From source file:de.juwimm.cms.test.hibernate.HbmTestImpl.java
public Principal loginSystemUser() { Principal p = null;// w w w . j a v a 2 s . co m if (loginContext == null) { log.info("Setting principal..."); //TODO login // System.setProperty( "java.security.auth.login.config", "C:\\svnroot\\juwimm-cms\\core\\src\\test\\jaas.conf" ); String encoded = "e"; SimpleCallbackHandler simpleCallbackHandler = new SimpleCallbackHandler(SYSTEM_USER, encoded); try { loginContext = new LoginContext("juwimm-cms-security-domain", simpleCallbackHandler); loginContext.login(); Subject s = loginContext.getSubject(); Iterator it = s.getPrincipals().iterator(); if (!s.getPrincipals().isEmpty()) { p = (Principal) it.next(); org.andromda.spring.PrincipalStore.set(p); } } catch (LoginException e) { if (log.isErrorEnabled()) { log.error("Could not login: " + e.getMessage(), e); } } } return p; }
From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManagerTest.java
/** * Tests that the authenticate method correctly interprets an * authentication success./*from ww w .jav a2 s .c o m*/ * */ public void testSaslAuthenticationSuccess() throws Exception { SaslServer testServer = createTestSaslServer(true, false); AuthenticationResult result = _manager.authenticate(testServer, "12345".getBytes()); final Subject subject = result.getSubject(); assertTrue(subject.getPrincipals().contains(new UsernamePrincipal("guest"))); assertEquals(AuthenticationStatus.SUCCESS, result.getStatus()); }
From source file:org.betaconceptframework.astroboa.test.engine.security.CmsLoginTest.java
@Test public void testAvailableRepositoriesReturnedWhenNoAuthorizedRepositoriesExist() { Subject subject = new Subject(); String identity = "testuser"; subject.getPrincipals().add(new IdentityPrincipal(identity)); repositoryService.login(TestConstants.TEST_REPOSITORY_ID, subject, null); SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext(); Assert.assertNotNull(securityContext, "Found no security context in Thread for logged in user " + identity); List<CmsRepository> availableRepositories = repositoryService.getAvailableCmsRepositories(); Assert.assertTrue(CollectionUtils.isNotEmpty(availableRepositories), "No available repositories for test"); List<String> authorizedRepositories = securityContext.getAuthorizedRepositories(); Assert.assertTrue(CollectionUtils.isNotEmpty(authorizedRepositories), "Authorized repositories must not be empty"); for (CmsRepository cmsRepository : availableRepositories) { Assert.assertTrue(authorizedRepositories.contains(cmsRepository.getId()), "Repository id " + cmsRepository.getId() + " was not found in authorized repositories " + authorizedRepositories.toString()); }/*ww w . j av a 2s . co m*/ }
From source file:org.sakaiproject.nakamura.api.lite.authorizable.User.java
/** * Does this user allow any of the principals identified in the subject to * impersonate it./*from w w w .j a va2s.c om*/ * * @param impersSubject * a subject containing principals to be tested * @return true if this user allows one or more of the subjects to * impersonate it. */ // TODO: Unit test public boolean allowImpersonate(Subject impersSubject) { String impersonators = (String) getProperty(IMPERSONATORS_FIELD); if (impersonators == null) { return false; } Set<String> impersonatorSet = ImmutableSet.of(StringUtils.split(impersonators, ';')); for (Principal p : impersSubject.getPrincipals()) { if (ADMIN_USER.equals(p.getName()) || SYSTEM_USER.equals(p.getName()) || impersonatorSet.contains(p.getName())) { return true; } } return false; }