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:com.nulli.openam.plugins.NeoUniversalCondition.java

private JSONObject sanitizeParams(String params, String realm, Subject subject, String resourceName,
        Map<String, Set<String>> env) throws EntitlementException {
    JSONObject jsonParams = null;/*from ww  w .j a v a 2 s .c  om*/
    boolean requestHasParams = false;
    Map<String, String> reqParamMap = new LinkedHashMap<String, String>();

    SSOToken token = (SSOToken) subject.getPrivateCredentials().iterator().next();

    if (resourceName.split("\\?").length > 1) {
        requestHasParams = true;
        String urlQuery = resourceName.split("\\?")[1];
        String[] urlParams = urlQuery.split("&");
        for (String param : urlParams) {
            int idx = param.indexOf("=");
            reqParamMap.put(param.substring(0, idx), param.substring(idx + 1));
        }
    }

    try {
        if (!params.isEmpty()) {
            jsonParams = new JSONObject(params);
            @SuppressWarnings("unchecked")
            Iterator<String> paramItr = jsonParams.keys();

            while (paramItr.hasNext()) {
                String paramKey = paramItr.next();
                String paramVal = jsonParams.get(paramKey).toString();
                if (paramVal.startsWith("__")) {
                    if (paramVal.equals("__userId")) {
                        if (!subject.getPrincipals().isEmpty()) {
                            String userId = getUserId(subject);
                            jsonParams.put(paramKey, userId);
                        } else {
                            throw new EntitlementException(EntitlementException.CONDITION_EVALUATION_FAILED,
                                    "could not find userId (required) from subject");
                        }
                    } else if (paramVal.equals("__resourceName")) {
                        jsonParams.put(paramKey, resourceName);
                    } else if (paramVal.equals("__realm")) {
                        jsonParams.put(paramKey, realm);
                    } else if (paramVal.startsWith("__env__")) {
                        String envParam = paramVal.substring(7);
                        String envParamVal = envMapStringify(envParam, env.get(envParam));
                        jsonParams.put(paramKey, envParamVal);
                    } else if (paramVal.startsWith("__token__")) {
                        String tokenProp = paramVal.substring(7);
                        String tokenPropVal = token.getProperty(tokenProp);
                        jsonParams.put(paramKey, tokenPropVal);
                    } else if (paramVal.startsWith("__token.")) {
                        String tokenMethod = paramVal.substring(6);
                        java.lang.reflect.Method method = token.getClass().getMethod(tokenMethod);
                        String methodRet = method.invoke(token).toString();
                        jsonParams.put(paramKey, methodRet);
                    } else if (paramVal.startsWith("__req__") && requestHasParams) {
                        String reqParam = paramVal.substring(7);
                        if (reqParamMap.containsKey(reqParam)) {
                            String reqParamVal = reqParamMap.get(reqParam);
                            jsonParams.put(paramKey, reqParamVal);
                        }
                    }
                }
            }

        }

    } catch (JSONException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SSOException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchMethodException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalArgumentException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvocationTargetException ex) {
        Logger.getLogger(NeoUniversalCondition.class.getName()).log(Level.SEVERE, null, ex);
    }

    return jsonParams;
}

From source file:org.josso.gl2.agent.SSOAgentValve.java

private void setAuthenticationResult(String name, Subject s, HttpServletRequest request) {
    log("**SSOAgentValve** finalise le flux http nom=" + name);
    _sessionMap.put(AUTH_TYPE_INFO_KEY, "JOSSO");
    CoyoteRequest httpReq = null;//from   ww w .  j a  va 2 s.  c om
    Session session = null;
    try {
        httpReq = getUnwrappedCoyoteRequest(request);
        session = getSession(httpReq);
    } catch (Exception e) {
        log("**SSOAgentValve** erreur sur la requte coyote ou la session ", e);
        return;
    }
    if (httpReq == null) {
        log("**SSOAgentValve** requte coyote vide");
        return;
    } else {
        for (Principal p : s.getPrincipals()) {
            if (p.getName().equals(name)) {
                httpReq.setUserPrincipal(p);
                httpReq.setAuthType("JOSSO");
                log("**SSOAgentValve** requte coyote avec principal p=" + p.getName());
                break;
            }

        }
    }
    if (session == null) {
        log("**SSOAgentValve** session active vide");
        return;
    } else {
        for (Principal p : s.getPrincipals()) {
            if (p.getName().equals(name)) {
                session.setPrincipal(p);
                session.setAuthType("JOSSO");
                log("**SSOAgentValve** session avec principal p=" + p.getName());
                break;
            }

        }
    }
}

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 {//  ww  w.  ja  va2 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:de.dal33t.powerfolder.clientserver.ServerClient.java

private byte[] prepareKerberosLogin() {
    try {//from w  ww.ja  v a 2  s  . c o  m
        Path outputFile = Controller.getTempFilesLocation().resolve("login.conf");

        if (Files.notExists(outputFile)) {
            InputStream configFile = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream("kerberos/login.conf");
            PathUtils.copyFromStreamToFile(configFile, outputFile);
        }

        System.setProperty("java.security.auth.login.config", outputFile.toAbsolutePath().toString());

        System.setProperty("java.security.krb5.realm",
                ConfigurationEntry.KERBEROS_SSO_REALM.getValue(getController()));
        String kdc = ConfigurationEntry.KERBEROS_SSO_KDC.getValue(getController());
        System.setProperty("java.security.krb5.kdc", kdc);

        LoginContext lc = new LoginContext("SignedOnUserLoginContext", new TextCallbackHandler());
        lc.login();
        Subject clientSubject = lc.getSubject();

        username = clientSubject.getPrincipals().iterator().next().getName();
        return Subject.doAs(clientSubject, new ServiceTicketGenerator());
    } catch (Exception e) {
        logWarning("Unable to login: " + e);
        return null;
    } finally {
        loggingIn.set(false);
    }
}

From source file:org.alfresco.filesys.auth.cifs.EnterpriseCifsAuthenticator.java

/**
 * Initialize the authenticator (after properties have been set)
 * /*w w  w . ja v a  2 s . c o m*/
 * @exception InvalidConfigurationException
 */
@Override
public void initialize() throws InvalidConfigurationException {
    super.initialize();

    // Check if Java API Kerberos debug output should be enabled

    if (this.kerberosDebug) {
        // Enable Kerberos API debug output

        System.setProperty("sun.security.jgss.debug", "true");
        System.setProperty("sun.security.krb5.debug", "true");
    }

    // Check if Kerberos is enabled
    if (m_krbRealm != null && m_krbRealm.length() > 0) {

        // Get the CIFS service account password
        if (m_password == null || m_password.length() == 0) {
            throw new InvalidConfigurationException("CIFS service account password not specified");
        }

        // Get the login configuration entry name
        if (m_loginEntryName == null || m_loginEntryName.length() == 0) {
            throw new InvalidConfigurationException("Invalid login entry specified");
        }

        // Create a login context for the CIFS server service

        try {
            // Login the CIFS server service

            m_loginContext = new LoginContext(m_loginEntryName, this);
            m_loginContext.login();
        } catch (LoginException ex) {
            // Debug

            if (logger.isErrorEnabled()) {
                logger.error("CIFS Kerberos authenticator error", ex);
            }

            throw new InvalidConfigurationException("Failed to login CIFS server service");
        }

        // Get the CIFS service account name from the subject

        Subject subj = m_loginContext.getSubject();
        Principal princ = subj.getPrincipals().iterator().next();

        m_accountName = princ.getName();

        if (logger.isDebugEnabled()) {
            logger.debug("Logged on using principal " + m_accountName);
        }

        // Create the Oid list for the SPNEGO NegTokenInit, include NTLMSSP for fallback

        m_mechTypes = new Vector<Oid>();

        // DEBUG

        if (logger.isDebugEnabled()) {
            logger.debug("Enabling mechTypes :-Kerberos5 MS-Kerberos5");
        }

        // Always enable Kerberos

        m_mechTypes.add(OID.KERBEROS5);
        m_mechTypes.add(OID.MSKERBEROS5);

        if (!disableNTLM) {
            m_mechTypes.add(OID.NTLMSSP);

            // DEBUG

            if (logger.isDebugEnabled()) {
                logger.debug(" Enabling NTLMSSP");
            }
        }

        // Indicate that SPNEGO security blobs are being used

        m_useRawNTLMSSP = false;
    }
    // Check if raw NTLMSSP or SPNEGO/NTLMSSP should be used
    else if (!m_useRawNTLMSSP) {
        // SPNEGO security blobs are being used

        // Create the Oid list for the SPNEGO NegTokenInit

        m_mechTypes = new Vector<Oid>();

        m_mechTypes.add(OID.NTLMSSP);

    } else {
        // Use raw NTLMSSP security blobs
    }

    // Make sure that either Kerberos support is enabled and/or the authentication component
    // supports MD4 hashed passwords

    if (!isKerberosEnabled() && (!(getAuthenticationComponent() instanceof NLTMAuthenticator)
            || getNTLMAuthenticator().getNTLMMode() != NTLMMode.MD4_PROVIDER)) {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "No valid CIFS authentication combination available, Either enable Kerberos support or use an SSO-enabled authentication component that supports MD4 hashed passwords");
        }
        // Throw an exception to stop the CIFS server startup

        throw new AlfrescoRuntimeException(
                "No valid CIFS authentication combination available, Either enable Kerberos support or use an SSO-enabled authentication component that supports MD4 hashed passwords");
    }
}

From source file:ca.nrc.cadc.vos.server.NodeDAOTest.java

private void compareNodes(String assertName, Node a, Node b) {
    Assert.assertNotNull(b);/*from   w w w. java 2s .c o  m*/
    Assert.assertEquals(assertName + "URI", a.getUri(), b.getUri());
    Assert.assertEquals(assertName + "type", a.getClass().getName(), b.getClass().getName());
    Assert.assertEquals(assertName + "name", a.getName(), b.getName());
    Subject subject = ((NodeID) b.appData).getOwner();
    Assert.assertNotNull(assertName + " owner", owner);
    Principal xp = null;
    for (Principal p : subject.getPrincipals()) {
        if (p instanceof X500Principal) {
            xp = p;
            break;
        }
    }
    Assert.assertNotNull(xp);
    Assert.assertTrue("caller==owner", AuthenticationUtil.equals(principal, xp));
}

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request//from   ww w . jav a2 s .  co  m
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

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

    /**
     * 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 gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } 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 (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.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);
            }

            /**
             * 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) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.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) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.AssertionConsumerProducer.java

private Subject buildSubjectFromResponse(ResponseType response) {

    Subject outSubject = new Subject();

    String issuerAlias = response.getIssuer().getValue();
    FederatedProvider issuer = getCotManager().lookupFederatedProviderByAlias(issuerAlias);

    if (response.getAssertionOrEncryptedAssertion().size() > 0) {

        AssertionType assertion = null;//from ww w.  ja  v  a  2  s. c  o  m

        if (response.getAssertionOrEncryptedAssertion().get(0) instanceof AssertionType) {
            assertion = (AssertionType) response.getAssertionOrEncryptedAssertion().get(0);
        } else {
            throw new RuntimeException("Response should be already decripted!");
        }

        // store subject identification information
        if (assertion.getSubject() != null) {

            List subjectContentItems = assertion.getSubject().getContent();

            for (Object o : subjectContentItems) {

                JAXBElement subjectContent = (JAXBElement) o;

                if (subjectContent.getValue() instanceof NameIDType) {

                    NameIDType nameId = (NameIDType) subjectContent.getValue();
                    // Create Subject ID Attribute
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding NameID to IDP Subject {" + nameId.getSPNameQualifier() + "}"
                                + nameId.getValue() + ":" + nameId.getFormat());
                    }
                    outSubject.getPrincipals().add(new SubjectNameID(nameId.getValue(), nameId.getFormat(),
                            nameId.getNameQualifier(), nameId.getSPNameQualifier()));

                } else if (subjectContent.getValue() instanceof BaseIDAbstractType) {
                    // TODO : Can we do something with this ?
                    throw new IllegalArgumentException("Unsupported Subject BaseID type "
                            + subjectContent.getValue().getClass().getName());

                } else if (subjectContent.getValue() instanceof EncryptedType) {
                    throw new IllegalArgumentException("Response should be already decripted!");

                } else if (subjectContent.getValue() instanceof SubjectConfirmationType) {
                    // TODO : Store subject confirmation data ?
                } else {
                    logger.error("Unknown subject content type : " + subjectContent.getClass().getName());
                }

            }

        }

        // store subject user attributes
        List<StatementAbstractType> stmts = assertion.getStatementOrAuthnStatementOrAuthzDecisionStatement();
        if (logger.isDebugEnabled())
            logger.debug("Found " + stmts.size() + " statements");

        for (StatementAbstractType stmt : stmts) {

            if (logger.isDebugEnabled())
                logger.debug("Processing statement " + stmts);

            if (stmt instanceof AttributeStatementType) {

                AttributeStatementType attrStmt = (AttributeStatementType) stmt;

                List attrs = attrStmt.getAttributeOrEncryptedAttribute();

                if (logger.isDebugEnabled())
                    logger.debug("Found " + attrs.size() + " attributes in attribute statement");

                for (Object attrOrEncAttr : attrs) {

                    if (attrOrEncAttr instanceof AttributeType) {

                        AttributeType attr = (AttributeType) attrOrEncAttr;

                        List<Object> attributeValues = attr.getAttributeValue();

                        if (logger.isDebugEnabled())
                            logger.debug("Processing attribute " + attr.getName());

                        for (Object attributeValue : attributeValues) {

                            if (logger.isDebugEnabled())
                                logger.debug("Processing attribute value " + attributeValue);

                            if (attributeValue instanceof String) {

                                if (logger.isDebugEnabled()) {
                                    logger.debug("Adding String Attribute Statement to IDP Subject "
                                            + attr.getName() + ":" + attr.getNameFormat() + "="
                                            + attr.getAttributeValue());
                                }

                                outSubject.getPrincipals()
                                        .add(new SubjectAttribute(attr.getName(), (String) attributeValue)

                                );

                            } else if (attributeValue instanceof Integer) {

                                if (logger.isDebugEnabled()) {
                                    logger.debug("Adding Integer Attribute Value to IDP Subject "
                                            + attr.getName() + ":" + attr.getNameFormat() + "="
                                            + attr.getAttributeValue());
                                }

                                outSubject.getPrincipals()
                                        .add(new SubjectAttribute(attr.getName(), (Integer) attributeValue)

                                );

                            } else if (attributeValue instanceof Element) {
                                Element e = (Element) attributeValue;
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Adding Attribute Statement to IDP Subject from DOM Element "
                                            + attr.getName() + ":" + attr.getNameFormat() + "="
                                            + e.getTextContent());
                                }

                                outSubject.getPrincipals()
                                        .add(new SubjectAttribute(attr.getName(), e.getTextContent())

                                );

                            } else if (attributeValue == null) {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Adding String Attribute Statement to IDP Subject "
                                            + attr.getName() + ":" + attr.getNameFormat() + "=" + "null");
                                }

                                outSubject.getPrincipals().add(new SubjectAttribute(attr.getName(), "")

                                );

                            } else {
                                logger.error(
                                        "Unknown Attribute Value type " + attributeValue.getClass().getName());
                            }

                        }
                    } else {
                        // TODO : Decrypt attribute using IDP's encryption key
                        logger.debug("Unknown attribute type " + attrOrEncAttr);
                    }
                }
            }

            // store subject authentication attributes
            if (stmt instanceof AuthnStatementType) {
                AuthnStatementType authnStmt = (AuthnStatementType) stmt;

                List<JAXBElement<?>> authnContextItems = authnStmt.getAuthnContext().getContent();

                for (JAXBElement<?> authnContext : authnContextItems) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authentiation Context to IDP Subject " + authnContext.getValue()
                                + ":" + SubjectAuthenticationAttribute.Name.AUTHENTICATION_CONTEXT);
                    }

                    outSubject.getPrincipals()
                            .add(new SubjectAuthenticationAttribute(
                                    SubjectAuthenticationAttribute.Name.AUTHENTICATION_CONTEXT,
                                    (String) authnContext.getValue()));

                }

                if (authnStmt.getAuthnInstant() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authentiation Attribute to IDP Subject "
                                + authnStmt.getAuthnInstant().toString() + ":"
                                + SubjectAuthenticationAttribute.Name.AUTHENTICATION_INSTANT);
                    }
                    outSubject.getPrincipals()
                            .add(new SubjectAuthenticationAttribute(
                                    SubjectAuthenticationAttribute.Name.AUTHENTICATION_INSTANT,
                                    authnStmt.getAuthnInstant().toString()));
                }

                if (authnStmt.getSessionIndex() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Adding Authentiation Attribute to IDP Subject " + authnStmt.getSessionIndex()
                                        + ":" + SubjectAuthenticationAttribute.Name.SESSION_INDEX);
                    }
                    outSubject.getPrincipals().add(new SubjectAuthenticationAttribute(
                            SubjectAuthenticationAttribute.Name.SESSION_INDEX, authnStmt.getSessionIndex()));
                }

                if (authnStmt.getSessionNotOnOrAfter() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authentiation Attribute to IDP Subject "
                                + authnStmt.getSessionNotOnOrAfter().toString() + ":"
                                + SubjectAuthenticationAttribute.Name.SESSION_NOT_ON_OR_AFTER);
                    }
                    outSubject.getPrincipals()
                            .add(new SubjectAuthenticationAttribute(
                                    SubjectAuthenticationAttribute.Name.SESSION_NOT_ON_OR_AFTER,
                                    authnStmt.getSessionNotOnOrAfter().toString()));
                }

                if (authnStmt.getSubjectLocality() != null
                        && authnStmt.getSubjectLocality().getAddress() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authentiation Attribute to IDP Subject "
                                + authnStmt.getSubjectLocality().getAddress() + ":"
                                + SubjectAuthenticationAttribute.Name.SUBJECT_LOCALITY_ADDRESS);
                    }
                    outSubject.getPrincipals()
                            .add(new SubjectAuthenticationAttribute(
                                    SubjectAuthenticationAttribute.Name.SUBJECT_LOCALITY_ADDRESS,
                                    authnStmt.getSubjectLocality().getAddress()));
                }

                if (authnStmt.getSubjectLocality() != null
                        && authnStmt.getSubjectLocality().getDNSName() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authentiation Attribute to IDP Subject "
                                + authnStmt.getSubjectLocality().getDNSName() + ":"
                                + SubjectAuthenticationAttribute.Name.SUBJECT_LOCALITY_DNSNAME);
                    }
                    outSubject.getPrincipals()
                            .add(new SubjectAuthenticationAttribute(
                                    SubjectAuthenticationAttribute.Name.SUBJECT_LOCALITY_DNSNAME,
                                    authnStmt.getSubjectLocality().getDNSName()));
                }
            }

            // Store subject authorization attributes
            if (stmt instanceof AuthzDecisionStatementType) {
                AuthzDecisionStatementType authzStmt = (AuthzDecisionStatementType) stmt;

                for (ActionType action : authzStmt.getAction()) {

                    if (action.getNamespace() != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Adding Authz Decision Action NS to IDP Subject " + action.getNamespace()
                                            + ":" + SubjectAuthorizationAttribute.Name.ACTION_NAMESPACE);
                        }
                        outSubject.getPrincipals().add(new SubjectAuthorizationAttribute(
                                SubjectAuthorizationAttribute.Name.ACTION_NAMESPACE, action.getNamespace()));
                    }

                    if (action.getValue() != null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Adding Authz Decision Action Value to IDP Subject " + action.getValue()
                                            + ":" + SubjectAuthorizationAttribute.Name.ACTION_VALUE);
                        }
                        outSubject.getPrincipals().add(new SubjectAuthorizationAttribute(
                                SubjectAuthorizationAttribute.Name.ACTION_VALUE, action.getValue()));
                    }

                }

                if (authzStmt.getDecision() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Adding Authz Decision Action to IDP Subject " + authzStmt.getDecision().value()
                                        + ":" + SubjectAuthorizationAttribute.Name.DECISION);
                    }
                    outSubject.getPrincipals().add(new SubjectAuthorizationAttribute(
                            SubjectAuthorizationAttribute.Name.DECISION, authzStmt.getDecision().value()));
                }

                if (authzStmt.getResource() != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Adding Authz Decision Action to IDP Subject " + authzStmt.getResource()
                                + ":" + SubjectAuthorizationAttribute.Name.RESOURCE);
                    }
                    outSubject.getPrincipals().add(new SubjectAuthorizationAttribute(
                            SubjectAuthorizationAttribute.Name.RESOURCE, authzStmt.getResource()));
                }

                // TODO: store evidence

            }

        }

    } else {
        logger.warn("No Assertion present within Response [" + response.getID() + "]");
    }

    SubjectAttribute idpAliasAttr = new SubjectAttribute("urn:org:atricore:idbus:sso:sp:idpAlias", issuerAlias);
    SubjectAttribute idpNameAttr = new SubjectAttribute("urn:org:atricore:idbus:sso:sp:idpName",
            issuer.getName());

    outSubject.getPrincipals().add(idpNameAttr);
    outSubject.getPrincipals().add(idpAliasAttr);

    if (outSubject != null && logger.isDebugEnabled()) {
        logger.debug("IDP Subject:" + outSubject);
    }

    return outSubject;
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@SuppressWarnings("unchecked")
@Test//w w w. j a  v a 2  s . co  m
public void testInitSecurityAwarePrototypeBean() {
    final DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition bd = new RootBeanDefinition(TestSecuredBean.class);
    bd.setScope(ConfigurableBeanFactory.SCOPE_PROTOTYPE);
    bd.setInitMethodName("init");
    lbf.registerBeanDefinition("test", bd);
    final Subject subject = new Subject();
    subject.getPrincipals().add(new TestPrincipal("user1"));

    TestSecuredBean bean = (TestSecuredBean) Subject.doAsPrivileged(subject, new PrivilegedAction() {
        @Override
        public Object run() {
            return lbf.getBean("test");
        }
    }, null);
    assertNotNull(bean);
    assertEquals("user1", bean.getUserName());
}

From source file:org.jspresso.framework.application.frontend.controller.AbstractFrontendController.java

/**
 * {@inheritDoc}//  ww  w .  j ava  2s.c  o m
 */
@Override
public void loggedIn(Subject subject) {
    UsernamePasswordHandler uph = getLoginCallbackHandler();
    if (!SecurityHelper.ANONYMOUS_USER_NAME.equals(uph.getUsername())) {
        if (uph.isRememberMe()) {
            rememberLogin(uph.getUsername(), uph.getPassword());
        } else {
            removeClientPreference(UP_KEY);
        }
    }
    String loginLocale = uph.getLanguage();
    if (loginLocale != null && !loginLocale.isEmpty()) {
        putClientPreference(LANG_KEY, loginLocale);
    } else {
        removeClientPreference(LANG_KEY);
    }
    String loginTimeZoneId = uph.getTimeZoneId();
    if (loginTimeZoneId != null && !loginTimeZoneId.isEmpty()) {
        putClientPreference(TZ_KEY, loginTimeZoneId);
    } else {
        removeClientPreference(TZ_KEY);
    }
    uph.clear();
    if (loginLocale != null) {
        for (Principal principal : subject.getPrincipals()) {
            if (principal instanceof UserPrincipal) {
                ((UserPrincipal) principal).putCustomProperty(UserPrincipal.LANGUAGE_PROPERTY, loginLocale);
            }
        }
    }
    if (loginTimeZoneId != null) {
        TimeZone loginTimeZone = TimeZone.getTimeZone(loginTimeZoneId);
        if (loginTimeZone != null) {
            getBackendController().setClientTimeZone(loginTimeZone);
        }
    }
    getBackendController().loggedIn(subject);
    execute(getLoginAction(), getLoginActionContext());
    if (workspaces != null) {
        Map<String, Workspace> filteredWorkspaces = new HashMap<>();
        for (Map.Entry<String, Workspace> workspaceEntry : workspaces.entrySet()) {
            Workspace workspace = workspaceEntry.getValue();
            // Must be put here so that ws that are not accessible
            // due to security restrictions are still translated.
            translateWorkspace(workspace);
            if (isAccessGranted(workspace)) {
                try {
                    pushToSecurityContext(workspace);
                    workspace.setSecurityHandler(this);
                    translateWorkspace(workspace);
                    filteredWorkspaces.put(workspaceEntry.getKey(), workspaceEntry.getValue());
                } finally {
                    restoreLastSecurityContextSnapshot();
                }
            }
        }
        getBackendController().installWorkspaces(filteredWorkspaces);
    }
}