Search in sources :

Example 1 with SPAccountMapper

use of com.sun.identity.saml2.plugins.SPAccountMapper 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 2 with SPAccountMapper

use of com.sun.identity.saml2.plugins.SPAccountMapper in project OpenAM by OpenRock.

the class SAML2Utils method getSPAccountMapper.

/**
     * Returns an <code>SPAccountMapper</code>
     *
     * @param realm      the realm name
     * @param spEntityID the entity id of the service provider
     * @return the <code>SPAccountMapper</code>
     * @throws SAML2Exception if the operation is not successful
     */
public static SPAccountMapper getSPAccountMapper(String realm, String spEntityID) throws SAML2Exception {
    String classMethod = "SAML2Utils.getSPAccountMapper: ";
    String spAccountMapperName = null;
    SPAccountMapper spAccountMapper = null;
    try {
        spAccountMapperName = getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.SP_ACCOUNT_MAPPER);
        if (spAccountMapperName == null) {
            spAccountMapperName = SAML2Constants.DEFAULT_SP_ACCOUNT_MAPPER_CLASS;
            if (debug.messageEnabled()) {
                debug.message(classMethod + "use " + SAML2Constants.DEFAULT_SP_ACCOUNT_MAPPER_CLASS);
            }
        }
        spAccountMapper = (SPAccountMapper) SPCache.spAccountMapperCache.get(spAccountMapperName);
        if (spAccountMapper == null) {
            spAccountMapper = (SPAccountMapper) Class.forName(spAccountMapperName).newInstance();
            SPCache.spAccountMapperCache.put(spAccountMapperName, spAccountMapper);
        } else {
            if (debug.messageEnabled()) {
                debug.message(classMethod + "got the SPAccountMapper from cache");
            }
        }
    } catch (Exception ex) {
        debug.error(classMethod + "Unable to get SP Account Mapper.", ex);
        throw new SAML2Exception(ex);
    }
    return spAccountMapper;
}
Also used : SystemConfigurationException(com.sun.identity.common.SystemConfigurationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) SessionException(com.sun.identity.plugin.session.SessionException) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) COTException(com.sun.identity.cot.COTException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SPAccountMapper(com.sun.identity.saml2.plugins.SPAccountMapper)

Example 3 with SPAccountMapper

use of com.sun.identity.saml2.plugins.SPAccountMapper in project OpenAM by OpenRock.

the class DoManageNameID method processManageNameIDRequest.

private static ManageNameIDResponse processManageNameIDRequest(ManageNameIDRequest mniRequest, String metaAlias, String remoteEntityID, Map paramsMap, String destination, String binding, HttpServletRequest request, HttpServletResponse response) {
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityID = null;
    String hostRole = null;
    Status status = null;
    String userID = null;
    try {
        hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
        hostRole = SAML2Utils.getHostEntityRole(paramsMap);
        SAML2Utils.verifyRequestIssuer(realm, hostEntityID, mniRequest.getIssuer(), mniRequest.getID());
        if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
            IDPAccountMapper idpAcctMapper = SAML2Utils.getIDPAccountMapper(realm, hostEntityID);
            userID = idpAcctMapper.getIdentity(mniRequest, hostEntityID, realm);
        } else if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
            SPAccountMapper spAcctMapper = SAML2Utils.getSPAccountMapper(realm, hostEntityID);
            userID = spAcctMapper.getIdentity(mniRequest, hostEntityID, realm);
        }
        if (userID == null) {
            status = SAML2Utils.generateStatus(SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null);
        } else {
            status = processManageNameIDRequest(mniRequest, realm, hostEntityID, remoteEntityID, hostRole, userID);
        }
    } catch (Exception e) {
        if (debug.messageEnabled()) {
            debug.message("DoManageNameID.processManageNameIDRequest:", e);
        }
        status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, e.toString());
    }
    ManageNameIDResponse mniResponse = null;
    try {
        String responseID = SAML2Utils.generateID();
        if (responseID == null) {
            debug.error(SAML2Utils.bundle.getString("failedToGenResponseID"));
        }
        mniResponse = pf.createManageNameIDResponse();
        mniResponse.setStatus(status);
        mniResponse.setID(responseID);
        mniResponse.setInResponseTo(mniRequest.getID());
        mniResponse.setVersion(SAML2Constants.VERSION_2_0);
        mniResponse.setIssueInstant(new Date());
        mniResponse.setIssuer(SAML2Utils.createIssuer(hostEntityID));
        if (destination != null && (destination.length() != 0)) {
            mniResponse.setDestination(XMLUtils.escapeSpecialCharacters(destination));
        }
    } catch (SAML2Exception e) {
        debug.error("Error : ", e);
    }
    if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE) && mniResponse.getStatus().getStatusCode().getValue().equals(SAML2Constants.SUCCESS)) {
        // invoke SPAdapter for post temination success
        postTerminationSuccess(hostEntityID, realm, request, response, userID, mniRequest, mniResponse, binding);
    }
    return mniResponse;
}
Also used : Status(com.sun.identity.saml2.protocol.Status) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IDPAccountMapper(com.sun.identity.saml2.plugins.IDPAccountMapper) ManageNameIDResponse(com.sun.identity.saml2.protocol.ManageNameIDResponse) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Date(java.util.Date) SPAccountMapper(com.sun.identity.saml2.plugins.SPAccountMapper)

Example 4 with SPAccountMapper

use of com.sun.identity.saml2.plugins.SPAccountMapper in project OpenAM by OpenRock.

the class SPACSUtils method getPrincipalWithoutLogin.

/**
     * Returns the username if there was one from the Assertion we were able to map into a local user account. Returns
     * null if not. Should only be used from the SP side. Should only be called in conjuncture with the Auth Module.
     * In addition, it performs what attribute federation it can.
     *
     * This method is a picked apart version of the "processResponse" function.
     */
public static String getPrincipalWithoutLogin(Subject assertionSubject, Assertion authnAssertion, String realm, String spEntityId, SAML2MetaManager metaManager, String idpEntityId, String storageKey) throws SAML2Exception {
    final EncryptedID encId = assertionSubject.getEncryptedID();
    final SPSSOConfigElement spssoconfig = metaManager.getSPSSOConfig(realm, spEntityId);
    final Set<PrivateKey> decryptionKeys = KeyUtil.getDecryptionKeys(spssoconfig);
    final SPAccountMapper acctMapper = SAML2Utils.getSPAccountMapper(realm, spEntityId);
    boolean needNameIDEncrypted = false;
    NameID nameId = assertionSubject.getNameID();
    String assertionEncryptedAttr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    if (assertionEncryptedAttr == null || !Boolean.parseBoolean(assertionEncryptedAttr)) {
        String idEncryptedStr = SAML2Utils.getAttributeValueFromSPSSOConfig(spssoconfig, SAML2Constants.WANT_NAMEID_ENCRYPTED);
        if (idEncryptedStr != null && Boolean.parseBoolean(idEncryptedStr)) {
            needNameIDEncrypted = true;
        }
    }
    if (needNameIDEncrypted && encId == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nameIDNotEncrypted"));
    }
    if (encId != null) {
        nameId = encId.decrypt(decryptionKeys);
    }
    SPSSODescriptorElement spDesc = null;
    try {
        spDesc = metaManager.getSPSSODescriptor(realm, spEntityId);
    } catch (SAML2MetaException ex) {
        SAML2Utils.debug.error("Unable to read SPSSODescription", ex);
    }
    if (spDesc == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    final String nameIDFormat = nameId.getFormat();
    if (nameIDFormat != null) {
        List spNameIDFormatList = spDesc.getNameIDFormat();
        if (CollectionUtils.isNotEmpty(spNameIDFormatList) && !spNameIDFormatList.contains(nameIDFormat)) {
            Object[] args = { nameIDFormat };
            throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "unsupportedNameIDFormatSP", args);
        }
    }
    final boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
    final boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
    final boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
    final boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && acctMapper.shouldPersistNameIDFormat(realm, spEntityId, idpEntityId, nameIDFormat));
    String userName = null;
    boolean isNewAccountLink = false;
    try {
        if (shouldPersistNameID) {
            try {
                userName = SAML2Utils.getDataStoreProvider().getUserID(realm, SAML2Utils.getNameIDKeyMap(nameId, spEntityId, idpEntityId, realm, SAML2Constants.SP_ROLE));
            } catch (DataStoreProviderException dse) {
                throw new SAML2Exception(dse.getMessage());
            }
        }
        //if we can't get an already linked account, see if we'll be generating a new one based on federated data
        if (userName == null) {
            userName = acctMapper.getIdentity(authnAssertion, spEntityId, realm);
            //we'll use this later to inform us
            isNewAccountLink = true;
        }
    } catch (SAML2Exception se) {
        return null;
    }
    //if we're new and we're persistent, store the federation data in the user pref
    if (isNewAccountLink && isPersistent) {
        try {
            writeFedData(nameId, spEntityId, realm, metaManager, idpEntityId, userName, storageKey);
        } catch (SAML2Exception se) {
            return userName;
        }
    }
    return userName;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) PrivateKey(java.security.PrivateKey) NameID(com.sun.identity.saml2.assertion.NameID) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) SPAccountMapper(com.sun.identity.saml2.plugins.SPAccountMapper) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) List(java.util.List) ArrayList(java.util.ArrayList) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 5 with SPAccountMapper

use of com.sun.identity.saml2.plugins.SPAccountMapper in project OpenAM by OpenRock.

the class SAML2 method shouldPersistNameID.

private boolean shouldPersistNameID(String spEntityId) throws SAML2Exception {
    final DefaultLibrarySPAccountMapper spAccountMapper = new DefaultLibrarySPAccountMapper();
    final String spEntityID = SPSSOFederate.getSPEntityId(metaAlias);
    final IDPSSODescriptorElement idpsso = SPSSOFederate.getIDPSSOForAuthnReq(realm, entityName);
    final SPSSODescriptorElement spsso = SPSSOFederate.getSPSSOForAuthnReq(realm, spEntityID);
    nameIDFormat = SAML2Utils.verifyNameIDFormat(nameIDFormat, spsso, idpsso);
    isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
    boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
    boolean ignoreProfile = SAML2PluginsUtils.isIgnoredProfile(realm);
    return isPersistent || (!isTransient && !ignoreProfile && spAccountMapper.shouldPersistNameIDFormat(realm, spEntityId, entityName, nameIDFormat));
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) DefaultLibrarySPAccountMapper(com.sun.identity.saml2.plugins.DefaultLibrarySPAccountMapper) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)4 SPAccountMapper (com.sun.identity.saml2.plugins.SPAccountMapper)4 DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)3 SessionException (com.sun.identity.plugin.session.SessionException)3 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)3 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)3 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)2 NameID (com.sun.identity.saml2.assertion.NameID)2 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)2 IOException (java.io.IOException)2 PrivateKey (java.security.PrivateKey)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ServletException (javax.servlet.ServletException)2 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)2 SystemConfigurationException (com.sun.identity.common.SystemConfigurationException)1 COTException (com.sun.identity.cot.COTException)1 SessionProvider (com.sun.identity.plugin.session.SessionProvider)1 Assertion (com.sun.identity.saml2.assertion.Assertion)1 Subject (com.sun.identity.saml2.assertion.Subject)1