Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.josso.jb4.agent.JBossCatalinaNativeRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the Gateway
 * as the authenticatd Principal./*from w  w w  .  j  a va  2 s.c o m*/
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

            Group callerPrincipal = new BaseRoleImpl("CallerPrincipal");
            callerPrincipal.addMember(ssoUser);
            // Add the "CallerPrincipal" group to the Subject so that JBoss can fetch user.
            subject.getPrincipals().add(callerPrincipal);

            logger.debug("Authenticated Subject: " + subject);

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = rm.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal);

            // Get the caching principal
            principal = getCachingPrincpal(rm, oldPrincipal, principal, credentials, subject);

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:org.betaconceptframework.astroboa.engine.service.security.AstroboaLogin.java

private void setupContextForInternalIdentityStore(String identityStoreRepositoryId) {

    //Since we are using the internal identity store, we must setup the security context
    //for the user who will be used to connect to the repository which represents the
    //identity store. This user is the SYSTEM user by default and thus we perform
    //an internal login without the need of the SYSTEM's password
    Subject subject = new Subject();

    //System identity
    subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

    //Grant SYSTEM all roles
    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
    }/*from  w w  w. j  av  a2  s .c  om*/
    subject.getPrincipals().add(rolesPrincipal);

    //Login using the Subject, the provided roles and SYSTEM's permanent key and get the authentication token
    authenticationTokenForSYSTEMofInternalIdentityStore = repositoryDao.login(identityStoreRepositoryId,
            subject, RepositoryRegistry.INSTANCE.getPermanentKeyForUser(identityStoreRepositoryId,
                    IdentityPrincipal.SYSTEM));

}

From source file:backtype.storm.blobstore.BlobStoreAclHandler.java

private boolean isNimbus(Subject who) {
    Set<Principal> principals;
    boolean isNimbusInstance = false;
    if (who != null) {
        principals = who.getPrincipals();
        for (Principal principal : principals) {
            if (principal instanceof NimbusPrincipal) {
                isNimbusInstance = true;
            }/*from ww  w .j av a2s .  com*/
        }
    }
    return isNimbusInstance;
}

From source file:org.josso.tc50.agent.CatalinaNativeRealm.java

/**
  * Construct and return a java.security.Principal instance
  * representing the authenticated user for the specified Subject. If no
  * such Principal can be constructed, return null.
  *//from  www  .  j  a v a2s.  c o  m
  * The Principal constructed is CatalinaSSOUser which is a SSOUser.
  * The Partner Application can access SSOUser-specific properties that are not available
  * in GenericPrincipal.
  *
  * @param subject The Subject representing the logged in user
  */
protected Principal createPrincipal(String username, Subject subject) {
    CatalinaSSOUser p = CatalinaSSOUser.newInstance(this, subject);

    if (requiresRoleMap) {
        // This is a Tomcat 5.0.30 ... !

        try {

            List<Principal> roles = new ArrayList<Principal>();

            Iterator principals = subject.getPrincipals().iterator();
            while (principals.hasNext()) {

                Principal principal = (Principal) principals.next();
                String principalClass = principal.getClass().getName();

                if (_roleClasses.contains(principalClass)) {
                    log.debug("Adding role : " + principal.getName());
                    roles.add(principal);
                }

                // Same as Jboss - that's a pretty clean solution
                if ((principal instanceof Group) && "Roles".equals(principal.getName())) {
                    Group grp = (Group) principal;
                    Enumeration en = grp.members();
                    while (en.hasMoreElements()) {
                        Principal roleP = (Principal) en.nextElement();
                        log.debug("Adding role : " + roleP.getName());
                        roles.add(roleP);
                    }

                }
            }

            // Only in Catalina 5.0.30!
            log.debug("Storing roles in parent roleMap");
            Map m = (Map) getRoleMapField().get(this);
            m.put(p, roles);

        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            return p;
        }
    }

    return p;
}

From source file:org.betaconceptframework.astroboa.security.jaas.AstroboaLoginModule.java

private void initializeAstroboaClientForIdentityStore(String identityStoreRepositoryId) {

    //We assume that identity store repository exists in the same Astroboa server this module runs
    AstroboaClient clientForInternalIdentityStore = new AstroboaClient();

    //Login as SYSTEM using Subject in order to avoid calling JAAS again
    //TODO This must be handled differently
    //In order to connect to IdentityStore, one must connect only as SYSTEM for now
    Subject subject = new Subject();

    //System identity
    subject.getPrincipals().add(new IdentityPrincipal(IdentityPrincipal.SYSTEM));

    Group rolesPrincipal = new CmsGroup(AstroboaPrincipalName.Roles.toString());

    for (CmsRole cmsRole : CmsRole.values()) {
        rolesPrincipal.addMember(new CmsPrincipal(CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(cmsRole, identityStoreRepositoryId)));
    }/* w w  w.  j a v a2  s  .  co  m*/

    subject.getPrincipals().add(rolesPrincipal);

    clientForInternalIdentityStore.login(identityStoreRepositoryId, subject, RepositoryRegistry.INSTANCE
            .getPermanentKeyForUser(identityStoreRepositoryId, IdentityPrincipal.SYSTEM));

    identityStore = clientForInternalIdentityStore.getIdentityStore();
}

From source file:backtype.storm.blobstore.BlobStoreTest.java

public Subject getSubject(String name) {
    Subject subject = new Subject();
    SingleUserPrincipal user = new SingleUserPrincipal(name);
    subject.getPrincipals().add(user);
    return subject;
}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test
public void testSuccess() throws Exception {

    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }//w  ww  .j a  va2  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(3, subject.getPrincipals().size());

    boolean foundKrb5User = false;
    boolean foundUser = false;
    boolean foundRole = false;
    boolean foundTicket = false;

    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof KerberosPrincipal) {
            assertEquals("hnelson@EXAMPLE.COM", pr.getName());
            foundKrb5User = true;
        } else if (pr instanceof UserPrincipal) {
            assertEquals("hnelson", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    for (Object crd : subject.getPrivateCredentials()) {
        if (crd instanceof KerberosTicket) {
            assertEquals("hnelson@EXAMPLE.COM", ((KerberosTicket) crd).getClient().getName());
            assertEquals("krbtgt/EXAMPLE.COM@EXAMPLE.COM", ((KerberosTicket) crd).getServer().getName());
            foundTicket = true;
            break;
        }
    }

    assertTrue("Principals should contains kerberos user", foundKrb5User);
    assertTrue("Principals should contains ldap user", foundUser);
    assertTrue("Principals should contains ldap role", foundRole);
    assertTrue("PricatePrincipals should contains kerberos ticket", foundTicket);

    assertTrue(module.logout());
    assertEquals("Principals should be gone as the user has logged out", 0, subject.getPrincipals().size());
}

From source file:org.polymap.core.security.SpnegoFilter.java

private void complex(HttpServletResponse httpResponse, String header) throws ServletException {
    // The data following the word Negotiate is the GSS-API data to process.
    byte gssapiData[] = new byte[0];
    try {/* w w w .  j a  va  2  s  .  c om*/
        gssapiData = com.sun.org.apache.xml.internal.security.utils.Base64
                .decode(header.substring(10).getBytes());
    } catch (Base64DecodingException e) {
        log.error("", e);
    }

    // Guard clause to check for the unsupported NTLM authentication mechanism.
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return;
    }

    /**
     * The server attempts to establish a security context. Establishment may
     * result in tokens that the server must return to the client. Tokens are
     * BASE-64 encoded GSS-API data.
     */
    GSSContext context = null;
    String outToken = null;

    try {
        GSSManager manager = GSSManager.getInstance();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2");
        GSSCredential serverCreds = manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, spnegoOid,
                GSSCredential.ACCEPT_ONLY);

        context = manager.createContext(serverCreds);

        byte tokenBytes[] = context.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = new String(Base64.encode(tokenBytes));
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the
     * "context initiator." In the case of the Kerberos mechanism, the context
     * initiator is the Kerberos principal of the client. Additionally, the
     * client may be delegating credentials.
     */
    if (context != null && context.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = context.getSrcName();
            Principal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);

            if (context.getCredDelegState()) {
                GSSCredential delegateCredential = context.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            // TODO
            // getSpnegoSession().setUser( clientGSSName.toString() );

            /**
             * A status code 200 status response can also carry a
             * "WWW-Authenticate" response header containing the final leg of an
             * authentication. In this case, the gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                httpResponse.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                httpResponse.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                return;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            httpResponse.addHeader("Client-Warning", gsse.getMessage());
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an
         * authentication error. If a 401 containing a "WWW-Authenticate" header
         * with "Negotiate" and gssapi-data is returned from the server, it is a
         * continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            httpResponse.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return;
        } else {
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");
}

From source file:org.apache.coheigea.cxf.kerberos.authentication.TokenPreAuthTest.java

private void validateServiceTicket(byte[] ticket) throws Exception {
    // Get the TGT for the service
    LoginContext loginContext = new LoginContext("bob", new KerberosCallbackHandler());
    loginContext.login();/*from   ww  w.j  a  v a  2s . com*/

    Subject serviceSubject = loginContext.getSubject();
    Set<Principal> servicePrincipals = serviceSubject.getPrincipals();
    assertFalse(servicePrincipals.isEmpty());

    // Handle the service ticket
    KerberosServiceExceptionAction serviceAction = new KerberosServiceExceptionAction(ticket,
            "bob@service.ws.apache.org");

    Subject.doAs(serviceSubject, serviceAction);
}

From source file:org.infoscoop.admin.web.PreviewImpersonationFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {
    request.setAttribute(IS_PREVIEW, Boolean.TRUE);

    Subject previewUser = new Subject();

    List<String> principals = new ArrayList<String>();

    String uidParam = request.getParameter(ISPrincipal.UID_PRINCIPAL);
    if (uidParam != null) {
        principals.add(ISPrincipal.UID_PRINCIPAL);
        principals.add(uidParam);//from   w  w  w .  ja  v  a2s.c om
        previewUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uidParam));
    }
    for (PrincipalDef def : SessionCreateConfig.getInstance().getPrincipalDefs()) {
        String[] principalValues = request.getParameterValues(def.getType());
        if (principalValues != null) {
            for (int i = 0; i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + def.getType() + ", name="
                            + principalValues[i] + ".");

                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(def.getType(), principalValues[i]));
            }
        }
    }

    // Principal retrieved from AccountManager set AuthenticationService
    AuthenticationService service = AuthenticationService.getInstance();
    IAccountManager manager = null;
    if (service != null)
        manager = service.getAccountManager();
    if (manager != null) {
        for (PrincipalDef def : manager.getPrincipalDefs()) {
            String roleType = def.getType();
            String[] principalValues = request.getParameterValues(roleType);

            for (int i = 0; principalValues != null && i < principalValues.length; i++) {
                if (log.isInfoEnabled())
                    log.info("Set preview principal: PrincipalType=" + roleType + ", name=" + principalValues[i]
                            + ".");
                principals.add(def.getType());
                principals.add(principalValues[i]);
                previewUser.getPrincipals().add(new ISPrincipal(roleType, principalValues[i]));
            }
        }
    }

    request.setAttribute(PRINCIPAL_PARAMS, principals);

    SetPrincipalHttpServletRequest reqwrapper = new SetPrincipalHttpServletRequest((HttpServletRequest) request,
            previewUser);
    filterChain.doFilter(reqwrapper, response);
}