Example usage for javax.security.auth Subject Subject

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

Introduction

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

Prototype

public Subject() 

Source Link

Document

Create an instance of a Subject with an empty Set of Principals and empty Sets of public and private credentials.

Usage

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

@Test
public void testNonAdminLogin() 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("cheese");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("foodie".toCharArray());
                }// ww w  .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(1, subject.getPrincipals().size());

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof UserPrincipal) {
            assertEquals("cheese", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertEquals("admin", pr.getName());
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    // cheese is not an admin so no roles should be returned
    assertFalse(foundRole);

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

From source file:edu.mit.oidc.web.StatusEndpoint.java

/**
 * Make a test call to the kerberos server to see if it's reachable.
 * //from   ww  w . ja  va 2 s .c  o  m
 * @return
 */
private Map<String, Map<String, Object>> getKerbStatus() {
    Map<String, Object> status = new HashMap<>();

    try {

        Krb5LoginModule krb = new Krb5LoginModule();

        Subject subject = new Subject();
        CallbackHandler callbackHandler = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                // ignore everything
            }
        };
        Map<String, Object> sharedState = ImmutableMap.of();
        Map<String, Object> options = new ImmutableMap.Builder().put("refreshKrb5Config", "true")
                .put("useTicketCache", "false").put("doNotPrompt", "true").put("useKeyTab", "true")
                .put("keyTab", getKeyTab()).put("storeKey", "false").put("principal", getPrincipal())
                .put("isInitiator", "true").build();

        krb.initialize(subject, callbackHandler, sharedState, options);

        boolean login = krb.login();
        status.put("success", login);
        status.put("subject", subject.getPrincipals());

    } catch (Exception e) {
        status.put("success", false);
        status.put("error", e.getMessage());
    }

    return ImmutableMap.of("kerberos", status);
}

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);/*from   w  ww .j a v  a2 s. com*/
    return subject;
}

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;
    }//  w ww .j  ava  2  s .  c  o  m
    Subject subject = new Subject();
    subject.getPrincipals().add(kp);
    subject.getPrivateCredentials().addAll(keys);
    return subject;
}

From source file:org.josso.jb4.agent.JBossCatalinaRealm.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 JAAS Gateway
 * Login Module as the authenticatd Principal.
 * 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/*from  w w  w . j  av a  2 s .  com*/
 */
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();
        Subject subject = new Subject();
        if (securityMgr.isValid(principal, credentials, subject)) {
            logger.debug("User: " + username + " is authenticated");

            // Get the authorized subject set by the isValid() call on succesful
            // authentication.
            //Subject activeSubject = securityMgr.getActiveSubject();

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

            Set principals = subject.getPrincipals(SSOUser.class);
            Iterator i = principals.iterator();
            while (i.hasNext()) {
                ssoUser = (SSOUser) i.next();
                break;
            }

            // 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);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:org.apache.ranger.services.kms.client.KMSClient.java

public List<String> getKeyList(final String keyNameMatching, final List<String> existingKeyList) {

    String providers[] = null;//from   w w  w  . j a  v  a2s.c o  m
    try {
        providers = createProvider(provider);
    } catch (IOException | URISyntaxException e) {
        return null;
    }
    final String errMsg = errMessage;
    List<String> lret = null;
    for (int i = 0; i < providers.length; i++) {
        lret = new ArrayList<String>();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting Kms Key list for keyNameMatching : " + keyNameMatching);
        }
        String uri = providers[i]
                + (providers[i].endsWith("/") ? KMS_LIST_API_ENDPOINT : ("/" + KMS_LIST_API_ENDPOINT));
        Client client = null;
        ClientResponse response = null;
        boolean isKerberos = false;
        try {
            ClientConfig cc = new DefaultClientConfig();
            cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
            client = Client.create(cc);

            if (authType != null && authType.equalsIgnoreCase(AUTH_TYPE_KERBEROS)) {
                isKerberos = true;
            }

            Subject sub = new Subject();
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + username);
                WebResource webResource = client.resource(uri);
                response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                LOG.info("Init Login: security not enabled, using username");
                sub = SecureClientLogin.login(username);
            } else {
                if (!StringUtils.isEmpty(rangerPrincipal) && !StringUtils.isEmpty(rangerKeytab)) {
                    LOG.info("Init Lookup Login: security enabled, using rangerPrincipal/rangerKeytab");
                    if (StringUtils.isEmpty(nameRules)) {
                        nameRules = "DEFAULT";
                    }
                    String shortName = new HadoopKerberosName(rangerPrincipal).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, rangerKeytab, nameRules);
                } else {
                    LOG.info("Init Login: using username/password");
                    String shortName = new HadoopKerberosName(username).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    String decryptedPwd = PasswordUtils.decryptPassword(password);
                    sub = SecureClientLogin.loginUserWithPassword(username, decryptedPwd);
                }
            }
            final WebResource webResource = client.resource(uri);
            response = Subject.doAs(sub, new PrivilegedAction<ClientResponse>() {
                @Override
                public ClientResponse run() {
                    return webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                }
            });

            if (LOG.isDebugEnabled()) {
                LOG.debug("getKeyList():calling " + uri);
            }
            if (response != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("getKeyList():response.getStatus()= " + response.getStatus());
                }
                if (response.getStatus() == 200) {
                    String jsonString = response.getEntity(String.class);
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    @SuppressWarnings("unchecked")
                    List<String> keys = gson.fromJson(jsonString, List.class);
                    if (keys != null) {
                        for (String key : keys) {
                            if (existingKeyList != null && existingKeyList.contains(key)) {
                                continue;
                            }
                            if (keyNameMatching == null || keyNameMatching.isEmpty()
                                    || key.startsWith(keyNameMatching)) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("getKeyList():Adding kmsKey " + key);
                                }
                                lret.add(key);
                            }
                        }
                        return lret;
                    }
                } else if (response.getStatus() == 401) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else if (response.getStatus() == 403) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri
                            + ", so returning null list");
                    String jsonString = response.getEntity(String.class);
                    LOG.info(jsonString);
                    lret = null;
                }
            } else {
                String msgDesc = "Unable to get a valid response for " + "expected mime type : ["
                        + EXPECTED_MIME_TYPE + "] URL : " + uri + " - got null response.";
                LOG.error(msgDesc);
                HadoopException hdpException = new HadoopException(msgDesc);
                hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                lret = null;
                throw hdpException;
            }
        } catch (HadoopException he) {
            lret = null;
            throw he;
        } catch (Throwable t) {
            String msgDesc = "Exception while getting Kms Key List. URL : " + uri;
            HadoopException hdpException = new HadoopException(msgDesc, t);
            LOG.error(msgDesc, t);
            hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null);
            lret = null;
            throw hdpException;
        } finally {
            if (response != null) {
                response.close();
            }

            if (client != null) {
                client.destroy();
            }

            if (lret == null) {
                if (i != providers.length - 1)
                    continue;
            }
        }
    }
    return lret;
}

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 {//from www. ja va2  s  . c o  m
        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.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override//from w ww.j a v  a2s . c  o m
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);
    }
}

From source file:com.fiveamsolutions.nci.commons.authentication.LoginModuleTest.java

@Test
public void testIt() throws Exception {
    String un = "user";
    String pw = "Password1";
    LoginModule module = new CommonLoginModule();
    Map<String, ?> options = new HashMap<String, Object>();
    Map<String, ?> sharedState = new HashMap<String, Object>();
    Subject subject = new Subject();
    CallbackHandler cbh = new MockCallbackHandler(true);

    module.initialize(subject, cbh, sharedState, options);

    try {//from ww  w  .j a v a2  s .c o  m
        module.login();
        fail();
    } catch (LoginException e) {
        // expected
    }
    assertTrue(sharedState.isEmpty());
    assertTrue(module.abort());

    cbh = new MockCallbackHandler(false);
    module.initialize(subject, cbh, sharedState, options);

    try {
        module.login();
        fail();
    } catch (LoginException e) {
        // expected
    }
    assertTrue(sharedState.isEmpty());
    assertTrue(module.abort());

    cbh = new MockCallbackHandler(un, "pass".toCharArray());
    module.initialize(subject, cbh, sharedState, options);

    try {
        module.login();
        fail();
    } catch (FailedLoginException e) {
        // expected
    }
    assertTrue(sharedState.isEmpty());
    assertTrue(module.abort());

    createUser(un, pw);
    try {
        module.login();
        fail();
    } catch (FailedLoginException e) {
        // expected
    }
    assertTrue(sharedState.isEmpty());
    assertTrue(module.abort());

    cbh = new MockCallbackHandler(un.toUpperCase(), pw.toCharArray());
    module.initialize(subject, cbh, sharedState, options);

    assertTrue(module.login());
    assertTrue(!sharedState.isEmpty());
    assertEquals(un, sharedState.get("javax.security.auth.login.name"));
    assertEquals(pw, new String((char[]) sharedState.get("javax.security.auth.login.password")));
    assertTrue(subject.getPrincipals().isEmpty());

    assertTrue(module.commit());
    assertTrue(!subject.getPrincipals().isEmpty());
    assertEquals(un, subject.getPrincipals().iterator().next().getName());

    assertTrue(module.logout());
    assertTrue(subject.getPrincipals().isEmpty());
}

From source file:org.josso.jb32.agent.JBossCatalinaRealm.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 JAAS Gateway
 * Login Module as the authenticatd Principal.
 * 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//from w w w  .ja  va  2  s .c  o  m
 */
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();

        Subject subject = new Subject();
        if (securityMgr.isValid(principal, passwordChars, subject)) {
            logger.debug("User: " + username + " is authenticated");

            // Get the authorized subject set by the isValid() call on succesful
            // authentication.
            // Subject activeSubject = securityMgr.getActiveSubject();

            // logger.debug("Authenticated Subject: " + activeSubject);

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

            Set principals = subject.getPrincipals(SSOUser.class);
            Iterator i = principals.iterator();
            while (i.hasNext()) {
                ssoUser = (SSOUser) i.next();
                break;
            }

            // 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 realmMapping = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = realmMapping.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + "to: " + principal);
            if (principal.equals(oldPrincipal) == false) {
                _userPrincipalMap.put(principal, oldPrincipal);
            }

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}