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.storm.security.auth.ClientAuthUtils.java

/**
 * Populate a subject from credentials using the IAutoCredentials.
 *
 * @param subject     the subject to populate or null if a new Subject should be created.
 * @param autos       the IAutoCredentials to call to populate the subject.
 * @param credentials the credentials to pull from
 * @return the populated subject.//from  w  ww .ja  v  a  2s  .c  o  m
 */
public static Subject populateSubject(Subject subject, Collection<IAutoCredentials> autos,
        Map<String, String> credentials) {
    try {
        if (subject == null) {
            subject = new Subject();
        }
        for (IAutoCredentials autoCred : autos) {
            autoCred.populateSubject(subject, credentials);
        }
        return insertWorkerTokens(subject, credentials);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.eclipse.ecr.runtime.jtajca.NuxeoContainer.java

/**
 * Creates a Geronimo pooled connection manager using a Geronimo transaction
 * manager./*  w  w w.j  av  a  2  s  .  c o  m*/
 * <p>
 * The pool uses the transaction manager for recovery, and when using
 * XATransactions for cache + enlist/delist.
 *
 * @throws NamingException
 */
protected static GenericConnectionManager createConnectionManager(ConnectionManagerConfiguration config)
        throws NamingException {
    TransactionSupport transactionSupport = new XATransactions(config.useTransactionCaching,
            config.useThreadCaching);
    // note: XATransactions -> TransactionCachingInterceptor ->
    // ConnectorTransactionContext casts transaction to Geronimo's
    // TransactionImpl (from TransactionManagerImpl)
    PoolingSupport poolingSupport = new PartitionedPool(config.maxPoolSize, config.minPoolSize,
            config.blockingTimeoutMillis, config.idleTimeoutMinutes, config.matchOne, config.matchAll,
            config.selectOneNoMatch, config.partitionByConnectionRequestInfo, config.partitionBySubject);
    final Subject subject = new Subject();
    SubjectSource subjectSource = new SubjectSource() {
        @Override
        public Subject getSubject() {
            return subject;
        }
    };
    ConnectionTrackingCoordinator connectionTracker = new ConnectionTrackingCoordinator();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); // NuxeoContainer.class.getClassLoader();

    return new GenericConnectionManager(transactionSupport, poolingSupport, subjectSource, connectionTracker,
            transactionManager, config.name, classLoader);
}

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

@Test
public void testRoleMappingParsing() throws Exception {
    Properties options = ldapLoginModuleOptions();
    options.put(LDAPOptions.ROLE_MAPPING, "admin = karaf, test; admin = another");
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("admin123".toCharArray());
                }/*www . j  ava 2  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(4, subject.getPrincipals().size());

    final List<String> roles = new ArrayList<String>(Arrays.asList("karaf", "test", "another"));

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal pr : subject.getPrincipals()) {
        if (pr instanceof UserPrincipal) {
            assertEquals("admin", pr.getName());
            foundUser = true;
        } else if (pr instanceof RolePrincipal) {
            assertTrue(roles.remove(pr.getName()));
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);
    assertTrue(roles.isEmpty());

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

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Get the currently logged in user.//from   w ww.ja  v  a 2s  .c o m
 * @return the logged in user
 * @throws IOException if login fails
 */
public synchronized static UserGroupInformation getLoginUser() throws IOException {
    if (loginUser == null) {
        try {
            Subject subject = new Subject();
            LoginContext login;
            if (isSecurityEnabled()) {
                login = newLoginContext(HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, subject);
            } else {
                login = newLoginContext(HadoopConfiguration.SIMPLE_CONFIG_NAME, subject);
            }
            login.login();
            loginUser = new UserGroupInformation(subject);
            loginUser.setLogin(login);
            loginUser.setAuthenticationMethod(
                    isSecurityEnabled() ? AuthenticationMethod.KERBEROS : AuthenticationMethod.SIMPLE);
            loginUser = new UserGroupInformation(login.getSubject());
            String fileLocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION);
            if (fileLocation != null && isSecurityEnabled()) {
                // load the token storage file and put all of the tokens into the
                // user.
                Credentials cred = Credentials.readTokenStorageFile(new Path("file:///" + fileLocation), conf);
                for (Token<?> token : cred.getAllTokens()) {
                    loginUser.addToken(token);
                }
            }
            loginUser.spawnAutoRenewalThreadForUserCreds();
        } catch (LoginException le) {
            throw new IOException("failure to login", le);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("UGI loginUser:" + loginUser);
        }
    }
    return loginUser;
}

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

@Test
public void testRoleMappingFqdn() throws Exception {
    Properties options = ldapLoginModuleOptions();
    options.put(LDAPOptions.ROLE_MAPPING,
            "cn=admin,ou=groups,dc=example,dc=com=karaf;cn=admin,ou=mygroups,dc=example,dc=com=another");
    options.put(LDAPOptions.ROLE_BASE_DN, "ou=groups,dc=example,dc=com");
    options.put(LDAPOptions.ROLE_SEARCH_SUBTREE, "true");
    options.put(LDAPOptions.ROLE_FILTER, "(member=%fqdn)");
    options.put(LDAPOptions.ROLE_NAME_ATTRIBUTE, "description");
    LDAPLoginModule module = new LDAPLoginModule();
    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("admin");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("admin123".toCharArray());
                }/*from   www  .j a  v a 2 s. co m*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
    assertTrue(module.commit());

    assertEquals(2, subject.getPrincipals().size());

    final List<String> roles = new ArrayList<String>(Arrays.asList("karaf"));

    boolean foundUser = false;
    boolean foundRole = false;
    for (Principal principal : subject.getPrincipals()) {
        if (principal instanceof UserPrincipal) {
            assertEquals("admin", principal.getName());
            foundUser = true;
        } else if (principal instanceof RolePrincipal) {
            assertTrue(roles.remove(principal.getName()));
            foundRole = true;
        }
    }
    assertTrue(foundUser);
    assertTrue(foundRole);
    assertTrue(roles.isEmpty());

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

From source file:org.apache.ranger.audit.provider.MiscUtil.java

public static void authWithConfig(String appName, Configuration config) {
    try {/*from   www . j a v a2  s. com*/
        if (config != null) {
            logger.info(
                    "Getting AppConfigrationEntry[] for appName=" + appName + ", config=" + config.toString());
            AppConfigurationEntry[] entries = config.getAppConfigurationEntry(appName);
            if (entries != null) {
                logger.info("Got " + entries.length + "  AppConfigrationEntry elements for appName=" + appName);
                for (AppConfigurationEntry appEntry : entries) {
                    logger.info("APP_ENTRY:getLoginModuleName()=" + appEntry.getLoginModuleName());
                    logger.info("APP_ENTRY:getControlFlag()=" + appEntry.getControlFlag());
                    logger.info("APP_ENTRY.getOptions()=" + appEntry.getOptions());
                }
            }

            LoginContext loginContext = new LoginContext(appName, new Subject(), null, config);
            logger.info("Login in for appName=" + appName);
            loginContext.login();
            logger.info("Principals after login=" + loginContext.getSubject().getPrincipals());
            logger.info("UserGroupInformation.loginUserFromSubject(): appName=" + appName + ", principals="
                    + loginContext.getSubject().getPrincipals());

            UserGroupInformation ugi = MiscUtil.createUGIFromSubject(loginContext.getSubject());
            if (ugi != null) {
                MiscUtil.setUGILoginUser(ugi, loginContext.getSubject());
            }

            // UserGroupInformation.loginUserFromSubject(loginContext
            // .getSubject());
            logger.info("POST UserGroupInformation.loginUserFromSubject UGI="
                    + UserGroupInformation.getLoginUser());
        }
    } catch (Throwable t) {
        logger.fatal("Error logging as appName=" + appName + ", config=" + config.toString() + ", error="
                + t.getMessage());
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.RepositoryDao.java

private void initializeIdentityStoreForRepository(CmsRepository cmsRepository) {

    if (StringUtils.isBlank(cmsRepository.getExternalIdentityStoreJNDIName())) {
        String identityStoreRepositoryId = cmsRepository.getIdentityStoreRepositoryId();

        if (StringUtils.isBlank(identityStoreRepositoryId)) {
            throw new CmsException(
                    "No external IdentityStore JNDI has been provided nor an identity store repository id for repository "
                            + cmsRepository.getId());
        }//from   w w w  . j a  v  a2  s.co  m

        if (!repositoryInfos.containsKey(identityStoreRepositoryId)) {
            throw new CmsException("Found no repository with id " + identityStoreRepositoryId
                    + ".Cannot initialize identity store for repository " + cmsRepository.getId());
        }

        CmsRepository cmsRepositoryIdentityStore = repositoryInfos.get(identityStoreRepositoryId);
        Subject subject = new Subject();
        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)));
        }

        subject.getPrincipals().add(rolesPrincipal);

        SecurityContext securityContext = new SecurityContext(identityStoreRepositoryId, subject, 30, null);

        RepositoryContext repositoryContext = new RepositoryContext(cmsRepositoryIdentityStore,
                securityContext);
        AstroboaClientContextHolder
                .registerClientContext(new AstroboaClientContext(repositoryContext, lazyLoader), true);
        cmsRepositoryInitializationManager.initializeIdentityStore(cmsRepository.getId(),
                cmsRepositoryIdentityStore);
        AstroboaClientContextHolder.clearContext();
    }
}

From source file:org.apache.ranger.audit.provider.MiscUtil.java

public static void authWithKerberos(String keytab, String principal, String nameRules) {

    if (keytab == null || principal == null) {
        return;/*from w  w w  . jav a 2 s . c  o  m*/
    }
    Subject serverSubject = new Subject();
    int successLoginCount = 0;
    String[] spnegoPrincipals = null;
    try {
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                logger.error("No principals found in keytab=" + keytab);
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        boolean useKeytab = true;
        if (!useKeytab) {
            logger.info("Creating UGI with subject");
            List<LoginContext> loginContexts = new ArrayList<LoginContext>();
            for (String spnegoPrincipal : spnegoPrincipals) {
                try {
                    logger.info("Login using keytab " + keytab + ", for principal " + spnegoPrincipal);
                    final KerberosConfiguration kerberosConfiguration = new KerberosConfiguration(keytab,
                            spnegoPrincipal);
                    final LoginContext loginContext = new LoginContext("", serverSubject, null,
                            kerberosConfiguration);
                    loginContext.login();
                    successLoginCount++;
                    logger.info("Login success keytab " + keytab + ", for principal " + spnegoPrincipal);
                    loginContexts.add(loginContext);
                } catch (Throwable t) {
                    logger.error("Login failed keytab " + keytab + ", for principal " + spnegoPrincipal, t);
                }
                if (successLoginCount > 0) {
                    logger.info("Total login success count=" + successLoginCount);
                    try {
                        UserGroupInformation.loginUserFromSubject(serverSubject);
                        // UserGroupInformation ugi =
                        // createUGIFromSubject(serverSubject);
                        // if (ugi != null) {
                        // setUGILoginUser(ugi, serverSubject);
                        // }
                    } catch (Throwable e) {
                        logger.error("Error creating UGI from subject. subject=" + serverSubject);
                    }
                } else {
                    logger.error(
                            "Total logins were successfull from keytab=" + keytab + ", principal=" + principal);
                }
            }
        } else {
            logger.info("Creating UGI from keytab directly. keytab=" + keytab + ", principal="
                    + spnegoPrincipals[0]);
            UserGroupInformation ugi = UserGroupInformation.loginUserFromKeytabAndReturnUGI(spnegoPrincipals[0],
                    keytab);
            MiscUtil.setUGILoginUser(ugi, null);
        }

    } catch (Throwable t) {
        logger.error("Failed to login with given keytab and principal", t);
    }

}

From source file:org.apache.hadoop.security.UserGroupInformation.java

/**
 * Log a user in from a keytab file. Loads a user identity from a keytab
 * file and logs them in. They become the currently logged-in user.
 * @param user the principal name to load from the keytab
 * @param path the path to the keytab file
 * @throws IOException if the keytab file can't be read
 *//*from  w  w w.j  a  v a 2 s .  c  o m*/
public synchronized static void loginUserFromKeytab(String user, String path) throws IOException {
    if (!isSecurityEnabled()) {
        return;
    }

    keytabFile = path;
    keytabPrincipal = user;
    Subject subject = new Subject();
    LoginContext login;
    long start = 0;
    // The renewer thread might have been spawned earlier if getLoginUser
    // was called with the loginUser as null. 
    // Just kill the thread. BTW loginUser is not null anymore and any 
    // future call to getLoginUser will not spawn the thread.
    if (renewerThread != null) {
        renewerThread.interrupt();
        shouldRunRenewerThread = false;
        renewerThread = null;
        LOG.info("Asked the TGT renewer thread to terminate");
    }
    try {
        login = newLoginContext(HadoopConfiguration.KEYTAB_KERBEROS_CONFIG_NAME, subject);
        start = System.currentTimeMillis();
        login.login();
        metrics.addLoginSuccess(System.currentTimeMillis() - start);
        loginUser = new UserGroupInformation(subject);
        loginUser.setLogin(login);
        loginUser.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    } catch (LoginException le) {
        if (start > 0) {
            metrics.addLoginFailure(System.currentTimeMillis() - start);
        }
        throw new IOException("Login failure for " + user + " from keytab " + path, le);
    }
    LOG.info("Login successful for user " + keytabPrincipal + " using keytab file " + keytabFile);
}

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;/*  w w  w  . j a v a 2  s .  c om*/

        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;
}