Search in sources :

Example 1 with DataStoreProviderException

use of com.sun.identity.plugin.datastore.DataStoreProviderException in project OpenAM by OpenRock.

the class FSAttributeStatementHelper method getAutoFedAttributeStatement.

/**
     * Gets a SAML <code>AttributeStatement</code> by using an
     * <code>AutoFederate</code> attribute that is configured in Local Provider.
     * @param realm The realm under which the entity resides.
     * @param entityID Host Provider's entity ID.
     * @param sub Liberty Subject.
     * @param ssoToken session of the user
     * @return Generated Auto Federate Attribute Statement.
     * @exception FSException if an error occurred
     */
public static AttributeStatement getAutoFedAttributeStatement(String realm, String entityID, FSSubject sub, Object ssoToken) throws FSException {
    IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
    BaseConfigType hostConfig = null;
    try {
        if (metaManager != null) {
            hostConfig = metaManager.getIDPDescriptorConfig(realm, entityID);
        }
    } catch (IDFFMetaException fae) {
        FSUtils.debug.error("FSAttributeStatementHelper.getAutoFed" + "AttributeStatement: IDFFMetaException ", fae);
        throw new FSException(fae);
    }
    String autoFedAttr = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostConfig, IFSConstants.AUTO_FEDERATION_ATTRIBUTE);
    if (autoFedAttr == null) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSAttributeStatementHelper.getAutoFed:" + "AttributeStatement: AutoFederate Attribute is null");
        }
        return null;
    }
    List values = new ArrayList();
    try {
        String userID = SessionManager.getProvider().getPrincipalName(ssoToken);
        DataStoreProvider provider = DataStoreProviderManager.getInstance().getDataStoreProvider(IFSConstants.IDFF);
        Set vals = provider.getAttribute(userID, autoFedAttr);
        Iterator iter = vals.iterator();
        while (iter.hasNext()) {
            values.add(getAttributeValue((String) iter.next()));
        }
    } catch (SessionException se) {
        FSUtils.debug.error("FSAttributeStatementHelper.getAutoFed" + "AttributeStatement: SessionException ", se);
        throw new FSException(se);
    } catch (DataStoreProviderException ie) {
        FSUtils.debug.error("FSAttributeStatementHelper.getAutoFed" + "AttributeStatement: DataStoreProviderException ", ie);
        throw new FSException(ie);
    }
    if (values == null || values.size() == 0) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSAtributeStatementHelper.getAuto:" + "FedAttributeStatement. No values for autofed attribute");
        }
        return null;
    }
    try {
        Attribute attribute = new Attribute(IFSConstants.AUTO_FED_ATTR, IFSConstants.assertionSAMLNameSpaceURI, values);
        List attributeList = new ArrayList();
        attributeList.add(attribute);
        return new AttributeStatement(sub, attributeList);
    } catch (SAMLException ex) {
        FSUtils.debug.error("FSAttributeStatementHelper.getAutoFed" + "AttributeStatement: SAMLException ", ex);
        throw new FSException(ex);
    }
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) Set(java.util.Set) Attribute(com.sun.identity.saml.assertion.Attribute) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) DataStoreProvider(com.sun.identity.plugin.datastore.DataStoreProvider) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) IDFFMetaManager(com.sun.identity.federation.meta.IDFFMetaManager) AttributeStatement(com.sun.identity.saml.assertion.AttributeStatement) FSException(com.sun.identity.federation.common.FSException) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with DataStoreProviderException

use of com.sun.identity.plugin.datastore.DataStoreProviderException in project OpenAM by OpenRock.

the class SPACSUtils method processResponse.

/**
     * Authenticates user with <code>Response</code>.
     * Auth session upgrade will be called if input session is
     * not null.
     * Otherwise, saml2 auth module is called. The name of the auth module
     * is retrieved from <code>SPSSOConfig</code>. If not found, "SAML2" will
     * be used.
     *
     * @param request HTTP Servlet request
     * @param response HTTP Servlet response.
     * @param out the print writer for writing out presentation
     * @param metaAlias metaAlias for the service provider
     * @param session input session object. It could be null.
     * @param respInfo <code>ResponseInfo</code> to be verified.
     * @param realm realm or organization name of the service provider.
     * @param hostEntityId hosted service provider Entity ID.
     * @param metaManager <code>SAML2MetaManager</code> instance for meta operation.
     * @param auditor a <code>SAML2EventLogger</code> auditor object to hook into
     *                tracking information for the saml request
     * @return <code>Object</code> which holds result of the session.
     * @throws SAML2Exception if the processing failed.
     */
public static Object processResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String metaAlias, Object session, ResponseInfo respInfo, String realm, String hostEntityId, SAML2MetaManager metaManager, SAML2EventLogger auditor) throws SAML2Exception {
    String classMethod = "SPACSUtils.processResponse: ";
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "Response : " + respInfo.getResponse());
    }
    Map smap = null;
    try {
        // check Response/Assertion and get back a Map of relevant data
        smap = SAML2Utils.verifyResponse(request, response, respInfo.getResponse(), realm, hostEntityId, respInfo.getProfileBinding());
    } catch (SAML2Exception se) {
        // invoke SPAdapter for failure
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
        throw se;
    }
    com.sun.identity.saml2.assertion.Subject assertionSubject = (com.sun.identity.saml2.assertion.Subject) smap.get(SAML2Constants.SUBJECT);
    NameID nameId = assertionSubject.getNameID();
    EncryptedID encId = assertionSubject.getEncryptedID();
    Assertion authnAssertion = (Assertion) smap.get(SAML2Constants.POST_ASSERTION);
    String sessionIndex = (String) smap.get(SAML2Constants.SESSION_INDEX);
    respInfo.setSessionIndex(sessionIndex);
    Integer authLevel = (Integer) smap.get(SAML2Constants.AUTH_LEVEL);
    Long maxSessionTime = (Long) smap.get(SAML2Constants.MAX_SESSION_TIME);
    String inRespToResp = (String) smap.get(SAML2Constants.IN_RESPONSE_TO);
    List assertions = (List) smap.get(SAML2Constants.ASSERTIONS);
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "Assertions : " + assertions);
    }
    SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, hostEntityId);
    // get mappers
    SPAccountMapper acctMapper = SAML2Utils.getSPAccountMapper(realm, hostEntityId);
    SPAttributeMapper attrMapper = SAML2Utils.getSPAttributeMapper(realm, hostEntityId);
    String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    boolean needAttributeEncrypted = getNeedAttributeEncrypted(assertionEncryptedAttr, spssoconfig);
    boolean needNameIDEncrypted = getNeedNameIDEncrypted(assertionEncryptedAttr, spssoconfig);
    Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
    if (needNameIDEncrypted && encId == null) {
        SAML2Utils.debug.error(classMethod + "process: NameID was not encrypted.");
        SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("nameIDNotEncrypted"));
        // invoke SPAdapter for failure
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
        throw se;
    }
    if (encId != null) {
        try {
            nameId = encId.decrypt(decryptionKeys);
        } catch (SAML2Exception se) {
            // invoke SPAdapter for failure
            invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
            throw se;
        }
    }
    respInfo.setNameId(nameId);
    SPSSODescriptorElement spDesc = null;
    try {
        spDesc = metaManager.getSPSSODescriptor(realm, hostEntityId);
    } catch (SAML2MetaException ex) {
        SAML2Utils.debug.error(classMethod, ex);
    }
    if (spDesc == null) {
        SAML2Exception se = new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_META_DATA_ERROR, se);
        throw se;
    }
    String nameIDFormat = nameId.getFormat();
    if (nameIDFormat != null) {
        List spNameIDFormatList = spDesc.getNameIDFormat();
        if ((spNameIDFormatList != null) && (!spNameIDFormatList.isEmpty()) && (!spNameIDFormatList.contains(nameIDFormat))) {
            Object[] args = { nameIDFormat };
            SAML2Exception se = new SAML2Exception(SAML2Utils.BUNDLE_NAME, "unsupportedNameIDFormatSP", args);
            invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.INVALID_RESPONSE, se);
            throw se;
        }
    }
    boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
    boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
    boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
    String existUserName = null;
    SessionProvider sessionProvider = null;
    try {
        sessionProvider = SessionManager.getProvider();
    } catch (SessionException se) {
        // invoke SPAdapter for failure
        SAML2Exception se2 = new SAML2Exception(se);
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
        throw se2;
    }
    if (session != null) {
        try {
            existUserName = sessionProvider.getPrincipalName(session);
        } catch (SessionException se) {
            // invoke SPAdapter for failure
            SAML2Exception se2 = new SAML2Exception(se);
            invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
            throw se2;
        }
    }
    String remoteHostId = authnAssertion.getIssuer().getValue();
    String userName = null;
    boolean isNewAccountLink = false;
    boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && acctMapper.shouldPersistNameIDFormat(realm, hostEntityId, remoteHostId, nameIDFormat));
    try {
        if (shouldPersistNameID) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "querying data store for existing federation links: realm = " + realm + " hostEntityID = " + hostEntityId + " remoteEntityID = " + remoteHostId);
            }
            try {
                userName = SAML2Utils.getDataStoreProvider().getUserID(realm, SAML2Utils.getNameIDKeyMap(nameId, hostEntityId, remoteHostId, realm, SAML2Constants.SP_ROLE));
            } catch (DataStoreProviderException dse) {
                SAML2Utils.debug.error(classMethod + "DataStoreProviderException whilst retrieving NameID " + "information", dse);
                throw new SAML2Exception(dse.getMessage());
            }
        }
        if (userName == null) {
            userName = acctMapper.getIdentity(authnAssertion, hostEntityId, realm);
            isNewAccountLink = true;
        }
    } catch (SAML2Exception se) {
        // invoke SPAdapter for failure
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_NO_USER_MAPPING, se);
        throw se;
    }
    if (userName == null && respInfo.isLocalLogin()) {
        // In case we just got authenticated locally, we should accept the freshly authenticated session's principal
        // as the username corresponding to the received assertion.
        userName = existUserName;
    }
    if (null != auditor) {
        auditor.setUserId(userName);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "process: userName =[" + userName + "]");
    }
    List attrs = null;
    for (Iterator it = assertions.iterator(); it.hasNext(); ) {
        Assertion assertion = (Assertion) it.next();
        List origAttrs = getSAMLAttributes(assertion, needAttributeEncrypted, decryptionKeys);
        if (origAttrs != null && !origAttrs.isEmpty()) {
            if (attrs == null) {
                attrs = new ArrayList();
            }
            attrs.addAll(origAttrs);
        }
    }
    Map attrMap = null;
    if (attrs != null) {
        try {
            attrMap = attrMapper.getAttributes(attrs, userName, hostEntityId, remoteHostId, realm);
        } catch (SAML2Exception se) {
            // invoke SPAdapter for failure
            invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_ATTRIBUTE_MAPPING, se);
            throw se;
        }
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "process: remoteHostId = " + remoteHostId);
        SAML2Utils.debug.message(classMethod + "process: attrMap = " + attrMap);
    }
    respInfo.setAttributeMap(attrMap);
    // return error code for local user login
    if (StringUtils.isEmpty(userName)) {
        // map the user to the existing session.
        if (session != null) {
            try {
                sessionProvider.invalidateSession(session, request, response);
            } catch (SessionException se) {
                SAML2Utils.debug.error("An error occurred while trying to invalidate session", se);
            }
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("noUserMapping"));
    }
    boolean writeFedInfo = isNewAccountLink && shouldPersistNameID;
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "userName : " + userName);
        SAML2Utils.debug.message(classMethod + "writeFedInfo : " + writeFedInfo);
    }
    AuthnRequest authnRequest = null;
    if (smap != null) {
        authnRequest = (AuthnRequest) smap.get(SAML2Constants.AUTHN_REQUEST);
    }
    if (inRespToResp != null && inRespToResp.length() != 0) {
        SPCache.requestHash.remove(inRespToResp);
    }
    Map sessionInfoMap = new HashMap();
    sessionInfoMap.put(SessionProvider.REALM, realm);
    sessionInfoMap.put(SessionProvider.PRINCIPAL_NAME, userName);
    // set client info. always use client IP address to prevent
    // reverse host lookup
    String clientAddr = ClientUtils.getClientIPAddress(request);
    sessionInfoMap.put(SessionProvider.HOST, clientAddr);
    sessionInfoMap.put(SessionProvider.HOST_NAME, clientAddr);
    sessionInfoMap.put(SessionProvider.AUTH_LEVEL, String.valueOf(authLevel));
    request.setAttribute(SessionProvider.ATTR_MAP, attrMap);
    try {
        session = sessionProvider.createSession(sessionInfoMap, request, response, null);
    } catch (SessionException se) {
        // invoke SPAdapter for failure
        int failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_GENERATION;
        int sessCode = se.getErrCode();
        if (sessCode == SessionException.AUTH_USER_INACTIVE) {
            failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_INACTIVE;
        } else if (sessCode == SessionException.AUTH_USER_LOCKED) {
            failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_USER_LOCKED;
        } else if (sessCode == SessionException.AUTH_ACCOUNT_EXPIRED) {
            failureCode = SAML2ServiceProviderAdapter.SSO_FAILED_AUTH_ACCOUNT_EXPIRED;
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPACSUtils.processResponse : error code=" + sessCode, se);
        }
        SAML2Exception se2 = new SAML2Exception(se);
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, failureCode, se2);
        throw se2;
    }
    // set metaAlias
    String[] values = { metaAlias };
    try {
        setAttrMapInSession(sessionProvider, attrMap, session);
        setDiscoBootstrapCredsInSSOToken(sessionProvider, authnAssertion, session);
        sessionProvider.setProperty(session, SAML2Constants.SP_METAALIAS, values);
    } catch (SessionException se) {
        // invoke SPAdapter for failure
        SAML2Exception se2 = new SAML2Exception(se);
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
        throw se2;
    }
    NameIDInfo info = null;
    String affiID = nameId.getSPNameQualifier();
    boolean isDualRole = SAML2Utils.isDualRole(hostEntityId, realm);
    AffiliationDescriptorType affiDesc = null;
    if (affiID != null && !affiID.isEmpty()) {
        affiDesc = metaManager.getAffiliationDescriptor(realm, affiID);
    }
    if (affiDesc != null) {
        if (!affiDesc.getAffiliateMember().contains(hostEntityId)) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
        }
        if (isDualRole) {
            info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, true);
        } else {
            info = new NameIDInfo(affiID, remoteHostId, nameId, SAML2Constants.SP_ROLE, true);
        }
    } else {
        if (isDualRole) {
            info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.DUAL_ROLE, false);
        } else {
            info = new NameIDInfo(hostEntityId, remoteHostId, nameId, SAML2Constants.SP_ROLE, false);
        }
    }
    Map props = new HashMap();
    String nameIDValueString = info.getNameIDValue();
    props.put(LogUtil.NAME_ID, info.getNameIDValue());
    try {
        userName = sessionProvider.getPrincipalName(session);
    } catch (SessionException se) {
        // invoke SPAdapter for failure
        SAML2Exception se2 = new SAML2Exception(se);
        invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.SSO_FAILED_SESSION_ERROR, se2);
        throw se2;
    }
    String[] data1 = { userName, nameIDValueString };
    LogUtil.access(Level.INFO, LogUtil.SUCCESS_FED_SSO, data1, session, props);
    // write fed info into data store
    if (writeFedInfo) {
        try {
            AccountUtils.setAccountFederation(info, userName);
        } catch (SAML2Exception se) {
            // invoke SPAdapter for failure
            invokeSPAdapterForSSOFailure(hostEntityId, realm, request, response, smap, respInfo, SAML2ServiceProviderAdapter.FEDERATION_FAILED_WRITING_ACCOUNT_INFO, se);
            throw se;
        }
        String[] data = { userName, "" };
        if (LogUtil.isAccessLoggable(Level.FINE)) {
            data[1] = info.toValueString();
        }
        LogUtil.access(Level.INFO, LogUtil.FED_INFO_WRITTEN, data, session, props);
    }
    String requestID = respInfo.getResponse().getInResponseTo();
    // save info in memory for logout
    saveInfoInMemory(sessionProvider, session, sessionIndex, metaAlias, info, IDPProxyUtil.isIDPProxyEnabled(requestID), isTransient);
    // invoke SP Adapter
    SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, realm);
    if (spAdapter != null) {
        boolean redirected = spAdapter.postSingleSignOnSuccess(hostEntityId, realm, request, response, out, session, authnRequest, respInfo.getResponse(), respInfo.getProfileBinding(), writeFedInfo);
        String[] value = null;
        if (redirected) {
            value = new String[] { "true" };
        } else {
            value = new String[] { "false" };
        }
        try {
            sessionProvider.setProperty(session, SAML2Constants.RESPONSE_REDIRECTED, value);
        } catch (SessionException ex) {
            SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
        } catch (UnsupportedOperationException ex) {
            SAML2Utils.debug.warning("SPSingleLogout.processResp", ex);
        }
    }
    String assertionID = authnAssertion.getID();
    if (respInfo.getProfileBinding().equals(SAML2Constants.HTTP_POST)) {
        SPCache.assertionByIDCache.put(assertionID, SAML2Constants.ONETIME);
        try {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(assertionID, SAML2Constants.ONETIME, ((Long) smap.get(SAML2Constants.NOTONORAFTER)).longValue() / 1000);
            }
        } catch (SAML2TokenRepositoryException se) {
            SAML2Utils.debug.error(classMethod + "There was a problem saving the assertionID to the SAML2 Token Repository for assertionID:" + assertionID, se);
        }
    }
    respInfo.setAssertion(authnAssertion);
    return session;
}
Also used : PrivateKey(java.security.PrivateKey) HashMap(java.util.HashMap) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) SPAccountMapper(com.sun.identity.saml2.plugins.SPAccountMapper) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SessionProvider(com.sun.identity.plugin.session.SessionProvider) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) NameID(com.sun.identity.saml2.assertion.NameID) Assertion(com.sun.identity.saml2.assertion.Assertion) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) AffiliationDescriptorType(com.sun.identity.saml2.jaxb.metadata.AffiliationDescriptorType) Subject(com.sun.identity.saml2.assertion.Subject) Subject(com.sun.identity.saml2.assertion.Subject) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SPAttributeMapper(com.sun.identity.saml2.plugins.SPAttributeMapper) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with DataStoreProviderException

use of com.sun.identity.plugin.datastore.DataStoreProviderException in project OpenAM by OpenRock.

the class DefaultLibrarySPAccountMapper method getAutoFedUser.

/**
     * Returns user for the auto federate attribute.
     *
     * @param realm Realm name.
     * @param entityID Hosted <code>EntityID</code>.
     * @param assertion <code>Assertion</code> from the identity provider.
     * @return Auto federation mapped user from the assertion auto federation <code>AttributeStatement</code>. if the
     * statement does not have the auto federation attribute then the NameID value will be used if use NameID as SP user
     * ID is enabled, otherwise null.
     */
protected String getAutoFedUser(String realm, String entityID, Assertion assertion, String decryptedNameID, Set<PrivateKey> decryptionKeys) throws SAML2Exception {
    if (!isAutoFedEnabled(realm, entityID)) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation is disabled.");
        }
        return null;
    }
    String autoFedAttribute = getAttribute(realm, entityID, SAML2Constants.AUTO_FED_ATTRIBUTE);
    if (autoFedAttribute == null || autoFedAttribute.isEmpty()) {
        debug.error("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation is enabled but the auto federation attribute is not configured.");
        return null;
    }
    if (debug.messageEnabled()) {
        debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is set to: " + autoFedAttribute);
    }
    Set<String> autoFedAttributeValue = null;
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Assertion does not have any attribute statements.");
        }
    } else {
        for (AttributeStatement statement : attributeStatements) {
            autoFedAttributeValue = getAttribute(statement, autoFedAttribute, decryptionKeys);
            if (autoFedAttributeValue != null && !autoFedAttributeValue.isEmpty()) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Found auto federation attribute value in Assertion: " + autoFedAttributeValue);
                }
                break;
            }
        }
    }
    if (autoFedAttributeValue == null || autoFedAttributeValue.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is not specified" + " as an attribute.");
        }
        if (!useNameIDAsSPUserID(realm, entityID)) {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: NameID as SP UserID was not enabled " + " and auto federation attribute " + autoFedAttribute + " was not found in the Assertion");
            }
            return null;
        } else {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Trying now to autofederate with nameID" + ", nameID =" + decryptedNameID);
            }
            autoFedAttributeValue = CollectionUtils.asSet(decryptedNameID);
        }
    }
    String autoFedMapAttribute = null;
    DefaultSPAttributeMapper attributeMapper = new DefaultSPAttributeMapper();
    Map<String, String> attributeMap = attributeMapper.getConfigAttributeMap(realm, entityID, SP);
    if (attributeMap == null || attributeMap.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: attribute map is not configured.");
        }
    } else {
        autoFedMapAttribute = attributeMap.get(autoFedAttribute);
    }
    if (autoFedMapAttribute == null) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation attribute map is not specified in config.");
        }
        // assume it is the same as the auto fed attribute name 
        autoFedMapAttribute = autoFedAttribute;
    }
    try {
        Map<String, Set<String>> map = new HashMap<>(1);
        map.put(autoFedMapAttribute, autoFedAttributeValue);
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Search map: " + map);
        }
        String userId = dsProvider.getUserID(realm, map);
        if (userId != null && !userId.isEmpty()) {
            return userId;
        } else {
            // return auto-federation attribute value as uid 
            if (isDynamicalOrIgnoredProfile(realm)) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper: dynamical user creation or ignore profile " + "enabled : uid=" + autoFedAttributeValue);
                }
                // return the first value as uid
                return autoFedAttributeValue.iterator().next();
            }
        }
    } catch (DataStoreProviderException dse) {
        if (debug.warningEnabled()) {
            debug.warning("DefaultLibrarySPAccountMapper.getAutoFedUser: Datastore provider exception", dse);
        }
    }
    return null;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement)

Example 4 with DataStoreProviderException

use of com.sun.identity.plugin.datastore.DataStoreProviderException in project OpenAM by OpenRock.

the class DefaultAttributeMapper method getAttributes.

/**
     * This method first mapps the Subject in the query to a local site
     * account using the AccountMapper defined in the SAML Service.
     * The source ID is used to find the appropriate AccountMapper.
     * It then calls the User Management API to obtain the attribute value
     * using the Session and the attribute name in the AttributeDesignator(s)
     * of the query. If there is no AttributeDesignator in the query,
     * attributes of services specified as userServiceNameList in
     * amSAML.properties will be returned.
     * <p>
     *
     * @param query the <code>AttributeQuery</code> object.
     * @param sourceID the Source Identifier.
     * @param token  User Session
     * @throws SAMLException if there is an error.
     */
public List getAttributes(AttributeQuery query, String sourceID, Object token) throws SAMLException {
    if ((query == null) || (sourceID == null) || (token == null)) {
        SAMLUtils.debug.message("DefaultAttributeMapper: null input.");
        throw new SAMLException(SAMLUtils.bundle.getString("nullInput"));
    }
    Map entries = (Map) SAMLServiceManager.getAttribute(SAMLConstants.PARTNER_URLS);
    SAMLServiceManager.SOAPEntry destSite = (SAMLServiceManager.SOAPEntry) entries.get(sourceID);
    String name = null;
    PartnerAccountMapper paMapper = destSite.getPartnerAccountMapper();
    if (paMapper != null) {
        Map map = paMapper.getUser(query, sourceID);
        name = (String) map.get(PartnerAccountMapper.NAME);
    }
    if (name == null) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("DefaultAttributeMapper: couldn't " + "map the subject to a local user.");
        }
        throw new SAMLException(SAMLUtils.bundle.getString("cannotMapSubject"));
    }
    if (SAMLUtils.debug.messageEnabled()) {
        SAMLUtils.debug.message("user=" + name);
    }
    // assume user in default root realm
    DataStoreProvider provider = null;
    try {
        provider = DataStoreProviderManager.getInstance().getDataStoreProvider(SAMLConstants.SAML);
    } catch (DataStoreProviderException de) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("DefaultAttributeMapper.getAttribute:", de);
        }
        throw new SAMLException(SAMLUtils.bundle.getString("cannotMapSubject"));
    }
    List attributes = new ArrayList();
    Attribute attribute = null;
    List attrValues = null;
    String attrValueString = null;
    String attrName = null;
    Set valueSet = null;
    Iterator valueIter = null;
    List designators = query.getAttributeDesignator();
    if ((designators == null) || (designators.isEmpty())) {
        String userAttrName = SystemConfigurationUtil.getProperty("userAttributeNameList");
        if ((userAttrName == null) || (userAttrName.length() == 0)) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("DefaultAttributeMapper: " + "userAttributeNameList is not defined " + "or empty.");
            }
            return attributes;
        }
        Set attrNames = new HashSet();
        StringTokenizer stk = new StringTokenizer(userAttrName, ",");
        while (stk.hasMoreTokens()) {
            attrNames.add(stk.nextToken().trim());
        }
        Map valueMap = null;
        try {
            valueMap = provider.getAttributes(name, attrNames);
        } catch (DataStoreProviderException ie) {
            if (SAMLUtils.debug.messageEnabled()) {
                SAMLUtils.debug.message("DefaultAttributeMapper: " + "DataStoreProviderException:", ie);
            }
            throw new SAMLException(ie.getMessage());
        }
        Set keySet = valueMap.keySet();
        String keyName = null;
        Iterator keyIter = keySet.iterator();
        while (keyIter.hasNext()) {
            keyName = (String) keyIter.next();
            valueSet = (Set) valueMap.get(keyName);
            valueIter = valueSet.iterator();
            attrValues = new ArrayList();
            while (valueIter.hasNext()) {
                attrValueString = SAMLUtils.makeStartElementTagXML("AttributeValue", true, true) + ((String) valueIter.next()) + SAMLUtils.makeEndElementTagXML("AttributeValue", true);
                attrValues.add(XMLUtils.toDOMDocument(attrValueString, SAMLUtils.debug).getDocumentElement());
            }
            if (!attrValues.isEmpty()) {
                attribute = new Attribute(keyName, SAMLConstants.ATTR_NAME_SPACE, attrValues);
                attributes.add(attribute);
            }
        }
    } else {
        Iterator iter = designators.iterator();
        AttributeDesignator designator = null;
        while (iter.hasNext()) {
            designator = (AttributeDesignator) iter.next();
            attrName = (String) designator.getAttributeName();
            try {
                valueSet = provider.getAttribute(name, attrName);
            } catch (DataStoreProviderException ie) {
                if (SAMLUtils.debug.messageEnabled()) {
                    SAMLUtils.debug.message("DefaultAttributeMapper: " + "DataStoreProviderException:", ie);
                }
                throw new SAMLException(ie.getMessage());
            }
            valueIter = valueSet.iterator();
            attrValues = new ArrayList();
            while (valueIter.hasNext()) {
                attrValueString = SAMLUtils.makeStartElementTagXML("AttributeValue", true, true) + ((String) valueIter.next()) + SAMLUtils.makeEndElementTagXML("AttributeValue", true);
                attrValues.add(XMLUtils.toDOMDocument(attrValueString, SAMLUtils.debug).getDocumentElement());
            }
            if (!attrValues.isEmpty()) {
                attribute = new Attribute(attrName, designator.getAttributeNamespace(), attrValues);
                attributes.add(attribute);
            }
        }
    }
    return attributes;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) HashSet(java.util.HashSet) Set(java.util.Set) Attribute(com.sun.identity.saml.assertion.Attribute) DataStoreProvider(com.sun.identity.plugin.datastore.DataStoreProvider) ArrayList(java.util.ArrayList) SAMLException(com.sun.identity.saml.common.SAMLException) StringTokenizer(java.util.StringTokenizer) AttributeDesignator(com.sun.identity.saml.assertion.AttributeDesignator) Iterator(java.util.Iterator) SAMLServiceManager(com.sun.identity.saml.common.SAMLServiceManager) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) Map(java.util.Map) HashSet(java.util.HashSet)

Example 5 with DataStoreProviderException

use of com.sun.identity.plugin.datastore.DataStoreProviderException in project OpenAM by OpenRock.

the class DefaultNameIdentifierMapper method getNameIdentifier.

/**
     * Returns name identifier for assertion subject based on user account.
     *
     * @param session the session of the user performing the operation.
     * @param sourceID source ID for the site from which the assertion
     *        originated.
     * @param destID destination ID for the site for which the assertion will be
     *     created.
     * @return a <code>NameIdentifier</code> for assertion subject.
     * @exception SAMLException if an error occurs
     */
public NameIdentifier getNameIdentifier(Object session, String sourceID, String destID, String nameIDFormat) throws SAMLException {
    if (SAMLUtils.debug.messageEnabled()) {
        SAMLUtils.debug.message("DefaultNameIdentifierMapper." + "getNameIdentifier: sourceID = " + sourceID + ", destID = " + destID);
    }
    if (SAMLUtils.debug.messageEnabled()) {
        SAMLUtils.debug.message("DefaultNameIdentifierMapper." + "getNameIdentifier: nameIDFormat = " + nameIDFormat);
    }
    try {
        String nameQualifier = XMLUtils.escapeSpecialCharacters((SessionManager.getProvider().getProperty(session, "Organization")[0]));
        String userID = SessionManager.getProvider().getPrincipalName(session);
        String name = null;
        if (nameIDFormat != null) {
            Map nameIDFormatAttrMap = (Map) SAMLServiceManager.getAttribute(SAMLConstants.NAME_ID_FORMAT_MAP);
            if ((nameIDFormatAttrMap != null) && (!nameIDFormatAttrMap.isEmpty()) && (nameIDFormatAttrMap.keySet().contains(nameIDFormat))) {
                String attrName = (String) nameIDFormatAttrMap.get(nameIDFormat);
                try {
                    DataStoreProvider dsProvider = DataStoreProviderManager.getInstance().getDataStoreProvider(SAMLConstants.SAML);
                    Set attrValues = dsProvider.getAttribute(userID, attrName);
                    if ((attrValues != null) && (!attrValues.isEmpty())) {
                        name = (String) attrValues.iterator().next();
                    }
                } catch (DataStoreProviderException dspe) {
                    if (SAMLUtils.debug.warningEnabled()) {
                        SAMLUtils.debug.warning("DefaultNameIdentifierMapper." + "getNameIdentifier:", dspe);
                    }
                }
            }
        }
        if (name == null) {
            name = XMLUtils.escapeSpecialCharacters(userID);
        } else {
            name = XMLUtils.escapeSpecialCharacters(name);
        }
        return new NameIdentifier(name, nameQualifier, nameIDFormat);
    } catch (SessionException sx) {
        SAMLUtils.debug.error("DefaultNameIdentifierMapper." + "getNameIdentifier: Invalid Session ", sx);
        return null;
    } catch (Exception ex) {
        SAMLUtils.debug.error("DefaultNameIdentifierMapper." + "getNameIdentifier:", ex);
        return null;
    }
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) Set(java.util.Set) NameIdentifier(com.sun.identity.saml.assertion.NameIdentifier) DataStoreProvider(com.sun.identity.plugin.datastore.DataStoreProvider) SessionException(com.sun.identity.plugin.session.SessionException) Map(java.util.Map) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException)

Aggregations

DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)35 Set (java.util.Set)26 HashSet (java.util.HashSet)20 Iterator (java.util.Iterator)18 Map (java.util.Map)15 HashMap (java.util.HashMap)12 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)9 SessionException (com.sun.identity.plugin.session.SessionException)8 ArrayList (java.util.ArrayList)8 List (java.util.List)7 SSOException (com.iplanet.sso.SSOException)6 AMIdentity (com.sun.identity.idm.AMIdentity)6 IdRepoException (com.sun.identity.idm.IdRepoException)6 SSOToken (com.iplanet.sso.SSOToken)5 DataStoreProvider (com.sun.identity.plugin.datastore.DataStoreProvider)5 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)5 NameID (com.sun.identity.saml2.assertion.NameID)5 SessionProvider (com.sun.identity.plugin.session.SessionProvider)4 SAMLException (com.sun.identity.saml.common.SAMLException)4 NameIdentifier (com.sun.identity.saml.assertion.NameIdentifier)3