List of usage examples for javax.security.auth Subject getPrincipals
public Set<Principal> getPrincipals()
From source file:org.apache.karaf.jaas.modules.ldap.LdapCaseInsensitiveDNTest.java
@Test public void testCaseInsensitiveDN() 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 ww . j a v a2 s . 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()); }
From source file:org.infoscoop.account.simple.SimpleAccountManager.java
public Subject getSubject(String userid) throws Exception { Account account = (Account) this.getUser(userid); if (account == null) return null; Subject loginUser = new Subject(); ISPrincipal p = new ISPrincipal(ISPrincipal.UID_PRINCIPAL, account.getUid()); p.setDisplayName(account.getName()); loginUser.getPrincipals().add(p); return loginUser; }
From source file:org.wso2.carbon.andes.authorization.service.andes.AndesAuthorizationPlugin.java
/** * Authorize access to broker/*from w w w . j a v a 2s. co m*/ * * @param objectType We only control access to virtual host * @param instance the accessing instance * @return Authorization result */ public Result access(ObjectType objectType, Object instance) { try { Subject subject = SecurityManager.getThreadSubject(); Principal principal = (Principal) (subject.getPrincipals().toArray())[0]; if (principal == null) { // No user associated with the thread return getDefault(); } // Allow access to virtual host for all logged in users. Authorization happens only if a user is // authenticated. // So, at this point, the user is logged in. if (objectType == ObjectType.VIRTUALHOST) { return Result.ALLOWED; } } catch (Exception e) { logger.error("Authorising access to broker failed.", e); } return Result.DENIED; }
From source file:org.wso2.carbon.andes.authorization.service.andes.QpidAuthorizationPlugin.java
/** * Authorize access to broker//from ww w .j a v a 2 s .co m * * @param objectType * We only control access to virtual host * @param instance * @return * Authorization result */ public Result access(ObjectType objectType, Object instance) { try { Subject subject = SecurityManager.getThreadSubject(); Principal principal = (Principal) (subject.getPrincipals().toArray())[0]; if (principal == null) { // No user associated with the thread return getDefault(); } // Allow access to virtual host for all logged in users. Authorization happens only if a user is authenticated. // So, at this point, the user is logged in. if (objectType == ObjectType.VIRTUALHOST) { return Result.ALLOWED; } } catch (Exception e) { // Do nothing } return Result.DENIED; }
From source file:org.apache.activemq.jaas.PropertiesLoginModuleTest.java
public void testLoginReload() throws Exception { File targetPropDir = new File("target/loginReloadTest"); File sourcePropDir = new File("src/test/resources"); File usersFile = new File(targetPropDir, "users.properties"); File groupsFile = new File(targetPropDir, "groups.properties"); //Set up initial properties FileUtils.copyFile(new File(sourcePropDir, "users.properties"), usersFile); FileUtils.copyFile(new File(sourcePropDir, "groups.properties"), groupsFile); LoginContext context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secret")); context.login();/*from ww w.j a va 2 s . c o m*/ Subject subject = context.getSubject(); //test initial principals assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(GroupPrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); //Modify the file and test that the properties are reloaded Thread.sleep(1000); FileUtils.copyFile(new File(sourcePropDir, "usersReload.properties"), usersFile); FileUtils.copyFile(new File(sourcePropDir, "groupsReload.properties"), groupsFile); FileUtils.touch(usersFile); FileUtils.touch(groupsFile); //Use new password to verify users file was reloaded context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secrets")); context.login(); subject = context.getSubject(); //Check that the principals changed assertEquals("Should have three principals", 2, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have one group principals", 1, subject.getPrincipals(GroupPrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.forgerock.openam.examples.SampleSubjectType.java
@Override public SubjectDecision evaluate(String realm, SubjectAttributesManager mgr, Subject subject, String resourceName, Map<String, Set<String>> environment) throws EntitlementException { boolean authorized = false; for (Principal principal : subject.getPrincipals()) { String userDn = principal.getName(); int start = userDn.indexOf('='); int end = userDn.indexOf(','); if (end <= start) { throw new EntitlementException(EntitlementException.CONDITION_EVALUTATION_FAILED, "Name is not a valid DN: " + userDn); }/*from w ww . j a v a 2 s. c o m*/ String userName = userDn.substring(start + 1, end); if (userName.equals(getName())) { authorized = true; } } return new SubjectDecision(authorized, Collections.EMPTY_MAP); }
From source file:org.apache.activemq.artemis.core.security.jaas.PropertiesLoginModuleTest.java
@Test public void testLoginReload() throws Exception { File targetPropDir = new File("target/loginReloadTest"); File usersFile = new File(targetPropDir, "users.properties"); File rolesFile = new File(targetPropDir, "roles.properties"); //Set up initial properties FileUtils.copyFile(new File(getClass().getResource("/users.properties").toURI()), usersFile); FileUtils.copyFile(new File(getClass().getResource("/roles.properties").toURI()), rolesFile); LoginContext context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secret")); context.login();//from ww w . ja v a 2 s. c om Subject subject = context.getSubject(); //test initial principals assertEquals("Should have three principals", 3, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have two group principals", 2, subject.getPrincipals(RolePrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); //Modify the file and test that the properties are reloaded Thread.sleep(1000); FileUtils.copyFile(new File(getClass().getResource("/usersReload.properties").toURI()), usersFile); FileUtils.copyFile(new File(getClass().getResource("/rolesReload.properties").toURI()), rolesFile); FileUtils.touch(usersFile); FileUtils.touch(rolesFile); //Use new password to verify users file was reloaded context = new LoginContext("PropertiesLoginReload", new UserPassHandler("first", "secrets")); context.login(); subject = context.getSubject(); //Check that the principals changed assertEquals("Should have three principals", 2, subject.getPrincipals().size()); assertEquals("Should have one user principal", 1, subject.getPrincipals(UserPrincipal.class).size()); assertEquals("Should have one group principals", 1, subject.getPrincipals(RolePrincipal.class).size()); context.logout(); assertEquals("Should have zero principals", 0, subject.getPrincipals().size()); }
From source file:org.forgerock.openam.examples.SampleConditionType.java
@Override public ConditionDecision evaluate(String realm, Subject subject, String resource, Map<String, Set<String>> environment) throws EntitlementException { boolean authorized = true; for (Principal principal : subject.getPrincipals()) { String userDn = principal.getName(); int start = userDn.indexOf('='); int end = userDn.indexOf(','); if (end <= start) { throw new EntitlementException(EntitlementException.CONDITION_EVALUTATION_FAILED, "Name is not a valid DN: " + userDn); }/*w ww.j a v a2s . c om*/ String userName = userDn.substring(start + 1, end); if (userName.length() < getNameLength()) { authorized = false; } } return new ConditionDecision(authorized, Collections.EMPTY_MAP); }
From source file:org.apache.ws.security.message.token.KerberosSecurity.java
/** * Retrieve a service ticket from a KDC using the Kerberos JAAS module, and set it in this * BinarySecurityToken.// ww w.j av a 2s . co 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" }); } // Store the TGT KerberosTicket tgt = getKerberosTicket(clientSubject, null); // Get the service ticket KerberosClientAction action = new KerberosClientAction(clientPrincipals.iterator().next(), serviceName); byte[] ticket = (byte[]) Subject.doAs(clientSubject, action); if (ticket == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "kerberosServiceTicketError"); } if (log.isDebugEnabled()) { log.debug("Successfully retrieved a service ticket"); } // Get the Service Ticket (private credential) KerberosTicket serviceTicket = getKerberosTicket(clientSubject, tgt); if (serviceTicket != null) { secretKey = serviceTicket.getSessionKey(); } setToken(ticket); if ("".equals(getValueType())) { setValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ); } }
From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java
/** {@inheritDoc} */ @Override// w ww . ja va 2s.c om protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse) throws ServletException, IOException { try { final String key = ExternalAuthentication.startExternalAuthentication(httpRequest); final X509Certificate[] certs = (X509Certificate[]) httpRequest .getAttribute("javax.servlet.request.X509Certificate"); log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0); if (certs == null || certs.length < 1) { log.error("No X.509 Certificates found in request"); httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, AuthnEventIds.NO_CREDENTIALS); ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); return; } final X509Certificate cert = certs[0]; log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'", cert.getSubjectDN().getName(), cert.getIssuerDN().getName()); if (trustEngine != null) { try { final BasicX509Credential cred = new BasicX509Credential(cert); cred.setEntityCertificateChain(Arrays.asList(certs)); if (trustEngine.validate(cred, new CriteriaSet())) { log.debug("Trust engine validated X.509 certificate"); } else { log.warn("Trust engine failed to validate X.509 certificate"); httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY, AuthnEventIds.INVALID_CREDENTIALS); ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); return; } } catch (final SecurityException e) { log.error("Exception raised by trust engine", e); httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e); ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); return; } } final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM); if (passthrough != null && Boolean.parseBoolean(passthrough)) { log.debug("Setting UI passthrough cookie"); final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1"); cookie.setPath(httpRequest.getContextPath()); cookie.setMaxAge(60 * 60 * 24 * 365); cookie.setSecure(true); httpResponse.addCookie(cookie); } final Subject subject = new Subject(); subject.getPublicCredentials().add(cert); subject.getPrincipals().add(cert.getSubjectX500Principal()); httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject); // final String revokeConsent = httpRequest // .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM); // if (revokeConsent != null // && ("1".equals(revokeConsent) || "true" // .equals(revokeConsent))) { // httpRequest.setAttribute( // ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE); // } ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse); } catch (final ExternalAuthenticationException e) { throw new ServletException("Error processing external authentication request", e); } }