Search in sources :

Example 16 with AuthnContext

use of com.sun.identity.saml2.assertion.AuthnContext in project OpenAM by OpenRock.

the class UtilProxySAMLAuthenticatorLookup method retrieveAuthenticationFromCache.

@Override
public void retrieveAuthenticationFromCache() throws SessionException, ServerFaultException, ClientFaultException {
    final String classMethod = "UtilProxySAMLAuthenticatorLookup.retrieveAuthenticationFromCache: ";
    // the second visit, the user has already authenticated
    // retrieve the cache authn request and relay state
    // We need the session to pass it to the IDP Adapter preSendResponse
    SessionProvider sessionProvider = SessionManager.getProvider();
    try {
        data.setSession(sessionProvider.getSession(request));
        data.getEventAuditor().setSSOTokenId(data.getSession());
    } catch (SessionException se) {
        SAML2Utils.debug.error("An error occurred while retrieving the session: " + se.getMessage());
        data.setSession(null);
    }
    // Get the cached Authentication Request and Relay State before
    // invoking the IDP Adapter
    CacheObject cacheObj;
    synchronized (IDPCache.authnRequestCache) {
        cacheObj = (CacheObject) IDPCache.authnRequestCache.get(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
    }
    data.setRelayState((String) IDPCache.relayStateCache.get(data.getRequestID()));
    if (!isSessionValid(sessionProvider)) {
        return;
    }
    // Invoke the IDP Adapter after the user has been authenticated
    if (preSendResponse(request, response, data)) {
        return;
    }
    synchronized (IDPCache.authnRequestCache) {
        cacheObj = (CacheObject) IDPCache.authnRequestCache.remove(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setAuthnRequest((AuthnRequest) cacheObj.getObject());
    }
    synchronized (IDPCache.idpAuthnContextCache) {
        cacheObj = (CacheObject) IDPCache.idpAuthnContextCache.remove(data.getRequestID());
    }
    if (cacheObj != null) {
        data.setMatchingAuthnContext((AuthnContext) cacheObj.getObject());
    }
    data.setRelayState((String) IDPCache.relayStateCache.remove(data.getRequestID()));
    if (data.getAuthnRequest() == null) {
        authNotAvailable();
        return;
    }
    SAML2Utils.debug.message("{} RequestID= {}", classMethod, data.getRequestID());
    boolean isSessionUpgrade = false;
    if (CollectionUtils.isNotEmpty(IDPCache.isSessionUpgradeCache)) {
        isSessionUpgrade = IDPCache.isSessionUpgradeCache.contains(data.getRequestID());
    }
    if (isSessionUpgrade) {
        IDPSession oldSess = (IDPSession) IDPCache.oldIDPSessionCache.remove(data.getRequestID());
        String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
        if (StringUtils.isNotEmpty(sessionIndex)) {
            IDPCache.idpSessionsByIndices.put(sessionIndex, oldSess);
            final FedMonAgent agent = MonitorManager.getAgent();
            if (agent != null && agent.isRunning()) {
                final FedMonSAML2Svc saml2Svc = MonitorManager.getSAML2Svc();
                if (saml2Svc != null) {
                    saml2Svc.setIdpSessionCount(IDPCache.idpSessionsByIndices.size());
                }
            }
        }
    }
    if (data.getSession() != null) {
        // call multi-federation protocol to set the protocol
        MultiProtocolUtils.addFederationProtocol(data.getSession(), SingleLogoutManager.SAML2);
    }
    // generate assertion response
    data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
    NameIDPolicy policy = data.getAuthnRequest().getNameIDPolicy();
    String nameIDFormat = (policy == null) ? null : policy.getFormat();
    try {
        IDPSSOUtil.sendResponseToACS(request, response, out, data.getSession(), data.getAuthnRequest(), data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), nameIDFormat, data.getRelayState(), data.getMatchingAuthnContext());
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error(classMethod + "Unable to do sso or federation.", se);
        throw new ServerFaultException(data.getIdpAdapter(), SSO_OR_FEDERATION_ERROR, se.getMessage());
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IDPSession(com.sun.identity.saml2.profile.IDPSession) FedMonSAML2Svc(com.sun.identity.plugin.monitoring.FedMonSAML2Svc) NameIDPolicy(com.sun.identity.saml2.protocol.NameIDPolicy) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) SessionException(com.sun.identity.plugin.session.SessionException) CacheObject(com.sun.identity.saml2.profile.CacheObject) FedMonAgent(com.sun.identity.plugin.monitoring.FedMonAgent) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 17 with AuthnContext

use of com.sun.identity.saml2.assertion.AuthnContext in project OpenAM by OpenRock.

the class DefaultSPAuthnContextMapper method getRequestedAuthnContext.

/**
     * Returns the <code>RequestedAuthnContext</code> object.
     *
     * The RequestedAuthContext is created based on the query parameters
     * AuthnContextClassRef and AuthComparison  in the request
     * and authnContext attribute ,
     * spAuthncontextClassrefMapping, and  authComparison
     * attribute, spAuthncontextComparisonType ,  
     * set in the Service Provider Extended Configuration.
     * If the AuthnContext Class Reference cannot be determined then
     * the default value
     * urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTranstport
     * will be used. AuthnComparsion defaults to "exact" if no value
     * is specified.
     *
     * @param realm  Realm or Organization of the Service Provider.
     * @param hostEntityID Entity ID of the Service Provider.
     * @param paramsMap Map containing key/value pairs of parameters.
     *        The key/value pairs are those accepted during SP SSO
     *        initiation.
     * @throws SAML2Exception if an error occurs.
     */
public RequestedAuthnContext getRequestedAuthnContext(String realm, String hostEntityID, Map paramsMap) throws SAML2Exception {
    // Read the AuthnContext Class Reference passed as query string
    // to SP 
    List authContextClassRef = (List) paramsMap.get(SAML2Constants.AUTH_CONTEXT_CLASS_REF);
    List authLevelList = ((List) paramsMap.get(SAML2Constants.AUTH_LEVEL));
    Integer authLevel = null;
    if (authLevelList != null && !authLevelList.isEmpty()) {
        try {
            authLevel = new Integer((String) authLevelList.iterator().next());
        } catch (NumberFormatException nfe) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("not a valid integer", nfe);
            }
        } catch (Exception e) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("error getting " + "integer object", e);
            }
        }
    }
    if (authLevel == null) {
        authLevel = getAuthLevelFromAdvice(paramsMap);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("authLevel in Query:" + authLevel);
        SAML2Utils.debug.message("authContextClassRef in Query:" + authContextClassRef);
    }
    // Retreived the cached AuthClass Ref / Auth Level Map
    Map authRefMap = getAuthRefMap(realm, hostEntityID);
    List authCtxList = new ArrayList();
    // create a List of AuthnContext Class Reference
    if (authContextClassRef != null && !authContextClassRef.isEmpty()) {
        Iterator i = authContextClassRef.iterator();
        while (i.hasNext()) {
            String authClassRef = prefixIfRequired((String) i.next());
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("DefaultSPAuthnContextMapper: " + "authClassRef=" + authClassRef);
            }
            authCtxList.add(authClassRef);
        }
    }
    if (authLevel != null) {
        Set authCtxSet = authRefMap.keySet();
        Iterator i = authCtxSet.iterator();
        while (i.hasNext()) {
            String className = (String) i.next();
            if (DEFAULT.equals(className) || DEFAULT_CLASS_REF.equals(className)) {
                continue;
            }
            Integer aLevel = (Integer) authRefMap.get(className);
            if (aLevel != null && aLevel.intValue() >= authLevel.intValue()) {
                authCtxList.add(className);
            }
        }
    }
    if ((authCtxList == null || authCtxList.isEmpty()) && (authRefMap != null && !authRefMap.isEmpty())) {
        String defaultClassRef = (String) authRefMap.get(DEFAULT_CLASS_REF);
        if (defaultClassRef != null) {
            authCtxList.add(defaultClassRef);
        } else {
            Set authCtxSet = authRefMap.keySet();
            Iterator i = authCtxSet.iterator();
            while (i.hasNext()) {
                String val = (String) i.next();
                if (val != null && !val.equals(DEFAULT)) {
                    authCtxList.add(val);
                }
            }
        }
    }
    // if list empty set the default
    if (authCtxList.isEmpty()) {
        authCtxList.add(SAML2Constants.CLASSREF_PASSWORD_PROTECTED_TRANSPORT);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPCache.authContextHash is: " + SPCache.authContextHash);
        SAML2Utils.debug.message("authCtxList is: " + authCtxList);
    }
    // Retrieve Auth Comparison from Query parameter
    String authCtxComparison = SPSSOFederate.getParameter(paramsMap, SAML2Constants.SP_AUTHCONTEXT_COMPARISON);
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("AuthComparison in Query:" + authCtxComparison);
    }
    if ((authCtxComparison == null) || !isValidAuthComparison(authCtxComparison)) {
        authCtxComparison = SAML2Utils.getAttributeValueFromSSOConfig(realm, hostEntityID, SAML2Constants.SP_ROLE, SAML2Constants.SP_AUTHCONTEXT_COMPARISON_TYPE);
        if ((authCtxComparison != null) && (!isValidAuthComparison(authCtxComparison))) {
            authCtxComparison = null;
        }
    }
    RequestedAuthnContext reqCtx = ProtocolFactory.getInstance().createRequestedAuthnContext();
    reqCtx.setAuthnContextClassRef(authCtxList);
    reqCtx.setComparison(authCtxComparison);
    return reqCtx;
}
Also used : RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext) Set(java.util.Set) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 18 with AuthnContext

use of com.sun.identity.saml2.assertion.AuthnContext in project OpenAM by OpenRock.

the class DefaultSPAuthnContextMapper method getAuthLevel.

/**
     * Returns the auth level for the AuthContext
     *
     * @param reqCtx  the RequestedAuthContext object.
     * @param authnContext  the AuthnContext object.
     * @param realm the realm or organization to 
     *    retreive the authncontext.
     * @param hostEntityID the Service Provider Identity String.
     * @param idpEntityID the Identity Provider Identity String.
     * @return authlevel an integer value.
     * @throws SAML2Exception if there is an error.
     */
public int getAuthLevel(RequestedAuthnContext reqCtx, AuthnContext authnContext, String realm, String hostEntityID, String idpEntityID) throws SAML2Exception {
    Map authRefMap = (Map) SPCache.authContextHash.get(hostEntityID + "|" + realm);
    if (authRefMap == null || authRefMap.isEmpty()) {
        authRefMap = getAuthRefMap(realm, hostEntityID);
    }
    int authLevel = 0;
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:hostEntityID:" + hostEntityID);
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:realm:" + realm);
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:MAP:" + authRefMap);
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:HASH:" + SPCache.authContextHash);
    }
    String authnClassRef = null;
    if (authnContext != null) {
        authnClassRef = authnContext.getAuthnContextClassRef();
    }
    if ((reqCtx != null) && (authnClassRef != null) && (!isAuthnContextMatching(reqCtx.getAuthnContextClassRef(), authnClassRef, reqCtx.getComparison(), realm, hostEntityID))) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidAuthnContextClassRef"));
    }
    Integer authLevelInt = null;
    if ((authnClassRef != null) && (authnClassRef.length() > 0)) {
        if ((authRefMap != null) && (!authRefMap.isEmpty())) {
            authLevelInt = (Integer) authRefMap.get(authnClassRef);
        }
    } else {
        if ((authRefMap != null) && (!authRefMap.isEmpty())) {
            authLevelInt = (Integer) authRefMap.get(DEFAULT);
        }
    }
    if (authLevelInt != null) {
        authLevel = authLevelInt.intValue();
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:authnClRef:" + authnClassRef);
        SAML2Utils.debug.message("DefaultSPAuthnContextMapper:authLevel :" + authLevel);
    }
    return authLevel;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 19 with AuthnContext

use of com.sun.identity.saml2.assertion.AuthnContext in project OpenAM by OpenRock.

the class DefaultIDPAuthnContextMapper method getAuthnContextFromAuthLevel.

/**
     * Returns <code>AuthnContext</code> that matches the authenticated level.
     * @param authLevel user authenticated level
     * @param realm the realm to which the Identity Provider belongs
     * @param idpEntityID the Entity ID of the Identity Provider    
     *
     * @return <code>AuthnContext</code> object that matches authenticated
     *  level. Return default AuthnContext if authLevel is <code>null</code>.
     * @throws SAML2Exception if an error occurs.
     */
public AuthnContext getAuthnContextFromAuthLevel(String authLevel, String realm, String idpEntityID) throws SAML2Exception {
    String classRef = null;
    Map classRefLevelMap = null;
    if (IDPCache.classRefLevelHash != null) {
        classRefLevelMap = (Map) IDPCache.classRefLevelHash.get(idpEntityID + "|" + realm);
    }
    if (classRefLevelMap == null || classRefLevelMap.isEmpty()) {
        updateAuthnContextMapping(realm, idpEntityID);
        classRefLevelMap = (Map) IDPCache.classRefLevelHash.get(idpEntityID + "|" + realm);
        if (classRefLevelMap == null) {
            classRefLevelMap = new HashMap();
        }
    }
    if ((authLevel != null) && (authLevel.length() != 0)) {
        try {
            int level = Integer.parseInt(authLevel);
            Iterator iter = classRefLevelMap.keySet().iterator();
            while (iter.hasNext()) {
                String key = (String) iter.next();
                Integer value = (Integer) classRefLevelMap.get(key);
                if (value != null && (level == value.intValue())) {
                    classRef = key;
                    break;
                }
            }
        } catch (NumberFormatException ne) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("DefaultIDPAuthnContextMapper.getAuthnContextFromLevel:" + " input authLevel is not valid.", ne);
            }
        }
    }
    if (classRef == null) {
        classRef = (String) IDPCache.defaultClassRefHash.get(idpEntityID + "|" + realm);
        if (classRef == null) {
            classRef = SAML2Constants.CLASSREF_PASSWORD_PROTECTED_TRANSPORT;
        }
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("DefaultIDPAuthnContext.getClassRefFromLevel: authLevel=" + authLevel + ", classRef=" + classRef + ", classRefLevelMap=" + classRefLevelMap);
    }
    AuthnContext result = AssertionFactory.getInstance().createAuthnContext();
    result.setAuthnContextClassRef(classRef);
    return result;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Iterator(java.util.Iterator) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) AuthnContext(com.sun.identity.saml2.assertion.AuthnContext) RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext)

Example 20 with AuthnContext

use of com.sun.identity.saml2.assertion.AuthnContext in project OpenAM by OpenRock.

the class SAML2IDPProxyFRImpl method selectIDPBasedOnLOA.

private String selectIDPBasedOnLOA(List<String> idpList, String realm, AuthnRequest authnRequest) {
    String classMethod = "selectIdPBasedOnLOA";
    EntityDescriptorElement idpDesc = null;
    Set authnRequestContextSet = null;
    String idps = "";
    try {
        RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
        if (requestedAuthnContext == null) {
            //In this case we just simply return all the IdPs as each one should support a default AuthnContext.
            return StringUtils.join(idpList, " ");
        }
        List listOfAuthnContexts = requestedAuthnContext.getAuthnContextClassRef();
        debugMessage(classMethod, "listofAuthnContexts: " + listOfAuthnContexts);
        try {
            authnRequestContextSet = new HashSet(listOfAuthnContexts);
        } catch (Exception ex1) {
            authnRequestContextSet = new HashSet();
        }
        if ((idpList != null) && (!idpList.isEmpty())) {
            Iterator idpI = idpList.iterator();
            while (idpI.hasNext()) {
                String idp = (String) idpI.next();
                debugMessage(classMethod, "IDP is: " + idp);
                idpDesc = SAML2Utils.getSAML2MetaManager().getEntityDescriptor(realm, idp);
                if (idpDesc != null) {
                    ExtensionsType et = idpDesc.getExtensions();
                    if (et != null) {
                        debugMessage(classMethod, "Extensions found for idp: " + idp);
                        List idpExtensions = et.getAny();
                        if (idpExtensions != null || !idpExtensions.isEmpty()) {
                            debugMessage(classMethod, "Extensions content found for idp: " + idp);
                            Iterator idpExtensionsI = idpExtensions.iterator();
                            while (idpExtensionsI.hasNext()) {
                                EntityAttributesElement eael = (EntityAttributesElement) idpExtensionsI.next();
                                if (eael != null) {
                                    debugMessage(classMethod, "Entity Attributes found for idp: " + idp);
                                    List attribL = eael.getAttributeOrAssertion();
                                    if (attribL != null || !attribL.isEmpty()) {
                                        Iterator attrI = attribL.iterator();
                                        while (attrI.hasNext()) {
                                            AttributeElement ae = (AttributeElement) attrI.next();
                                            // TODO: Verify what type of element this is (Attribute or assertion)
                                            // For validation purposes
                                            List av = ae.getAttributeValue();
                                            if (av != null || !av.isEmpty()) {
                                                debugMessage(classMethod, "Attribute Values found for idp: " + idp);
                                                Iterator avI = av.iterator();
                                                while (avI.hasNext()) {
                                                    AttributeValueElement ave = (AttributeValueElement) avI.next();
                                                    if (ave != null) {
                                                        List contentL = ave.getContent();
                                                        debugMessage(classMethod, "Attribute Value Elements found for idp: " + idp + "-->" + contentL);
                                                        if (contentL != null || !contentL.isEmpty()) {
                                                            Set idpContextSet = trimmedListToSet(contentL);
                                                            debugMessage(classMethod, "idpContextSet = " + idpContextSet);
                                                            idpContextSet.retainAll(authnRequestContextSet);
                                                            if (idpContextSet != null && !idpContextSet.isEmpty()) {
                                                                idps = idp + " " + idps;
                                                                debugMessage(classMethod, "Extension Values found for idp " + idp + ": " + idpContextSet);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        debugMessage(classMethod, " No extensions found for IdP " + idp);
                    }
                } else {
                    debugMessage(classMethod, "Configuration for the idp " + idp + " was not found in this system");
                }
            }
        }
    } catch (SAML2MetaException me) {
        debugMessage(classMethod, "SOmething went wrong: " + me);
    }
    debugMessage(classMethod, " IDPList returns: " + idps);
    return idps.trim();
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) EntityAttributesElement(com.sun.identity.saml2.jaxb.metadataattr.EntityAttributesElement) EntityDescriptorElement(com.sun.identity.saml2.jaxb.metadata.EntityDescriptorElement) COTException(com.sun.identity.cot.COTException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext) ExtensionsType(com.sun.identity.saml2.jaxb.metadata.ExtensionsType) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) AttributeValueElement(com.sun.identity.saml2.jaxb.assertion.AttributeValueElement) AttributeElement(com.sun.identity.saml2.jaxb.assertion.AttributeElement) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) HashSet(java.util.HashSet)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)17 ArrayList (java.util.ArrayList)10 SessionException (com.sun.identity.plugin.session.SessionException)9 List (java.util.List)9 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)7 IOException (java.io.IOException)6 Date (java.util.Date)6 Map (java.util.Map)6 AuthnContext (com.sun.identity.saml2.assertion.AuthnContext)5 RequestedAuthnContext (com.sun.identity.saml2.protocol.RequestedAuthnContext)5 Response (com.sun.identity.saml2.protocol.Response)5 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)5 COTException (com.sun.identity.cot.COTException)4 Assertion (com.sun.identity.saml2.assertion.Assertion)4 AuthnStatement (com.sun.identity.saml2.assertion.AuthnStatement)4 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)4 IDPAuthnContextMapper (com.sun.identity.saml2.plugins.IDPAuthnContextMapper)4 HashMap (java.util.HashMap)4 Iterator (java.util.Iterator)4