Search in sources :

Example 36 with AuthnRequest

use of com.sun.identity.saml2.protocol.AuthnRequest in project OpenAM by OpenRock.

the class OAuth2Saml2GrantSPAdapter method postSingleSignOnSuccess.

/**
     * @{inheritDoc}
     */
public boolean postSingleSignOnSuccess(String hostedEntityID, String realm, HttpServletRequest request, HttpServletResponse response, PrintWriter out, Object session, AuthnRequest authnRequest, Response ssoResponse, String profile, boolean isFederation) throws SAML2Exception {
    AssertionImpl assertion = (AssertionImpl) ssoResponse.getAssertion().get(0);
    StringBuilder sb = new StringBuilder();
    try {
        //post assertion to the OAuth 2 token endpoint using the saml2 grant.
        sb.append("<form name=\"postForm\" action=\"");
        sb.append(hostedEntityID);
        if (hostedEntityID.endsWith("/")) {
            sb.append("oauth2/access_token");
        } else {
            sb.append("/oauth2/access_token");
        }
        sb.append("?realm=" + (StringUtils.isEmpty(realm) ? "/" : realm));
        sb.append("\" method=\"post\">");
        sb.append("<input type=\"hidden\" name=\"grant_type\" value=\"");
        sb.append(OAuth2Constants.SAML20.GRANT_TYPE_URI);
        sb.append("\">");
        sb.append("<input type=\"hidden\" name=\"assertion\" value=\"");
        sb.append(Base64.encode(assertion.toXMLString(false, false).getBytes("UTF-8")));
        sb.append("\">");
        sb.append("<input type=\"hidden\" name=\"client_id\" value=\"");
        sb.append(hostedEntityID);
        sb.append("\">");
        sb.append("</form>");
        sb.append("<script language=\"Javascript\">");
        sb.append("document.postForm.submit();");
        sb.append("</script>");
        out.print(sb.toString());
    } catch (UnsupportedEncodingException e) {
        SAML2Utils.debug.error("OAuth2Saml2GrantSPAdapter.postSingleSignOnSuccess: Unsuppored Encoding Exception: " + e.getMessage());
    } catch (IOException e) {
        SAML2Utils.debug.error("OAuth2Saml2GrantSPAdapter.postSingleSignOnSuccess: IOException: " + e.getMessage());
    }
    return true;
}
Also used : AssertionImpl(com.sun.identity.saml2.assertion.impl.AssertionImpl) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 37 with AuthnRequest

use of com.sun.identity.saml2.protocol.AuthnRequest in project OpenAM by OpenRock.

the class SAML2IDPProxyFRImpl method getPreferredIDP.

/**
     * Returns a list of preferred IDP providerIDs.
     * @param authnRequest original authnrequest
     * @param hostProviderID ProxyIDP providerID.
     * @param realm Realm
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @return a list of providerID's of the authenticating providers to be
     *     proxied or <code>null</code> to disable the proxying and continue
     *     for the localauthenticating provider.
     * @exception SAML2Exception if error occurs.
     */
public List getPreferredIDP(AuthnRequest authnRequest, String hostProviderID, String realm, HttpServletRequest request, HttpServletResponse response) throws SAML2Exception {
    // Entering the class and method
    String methodName = "getPreferredIDP";
    String classMethod = className + methodName + ":";
    debugMessage(methodName, "Entering.");
    Boolean isIdpFinderForAllSPsEnabled = isIDPFinderForAllSPs(realm, hostProviderID);
    // Start the logic to obtain the list of preferred IdPs
    try {
        // Inititate the metadata manager
        SAML2MetaManager sm = new SAML2MetaManager();
        if (sm == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
        }
        // Obtain the SP configuration
        try {
            spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, authnRequest.getIssuer().getValue().toString());
        } catch (SAML2MetaException sme) {
            SAML2Utils.debug.error(classMethod, sme);
            spSSODescriptor = null;
        }
        // Get the relay state from the request, if exists
        relayState = request.getParameter(SAML2Constants.RELAY_STATE);
        binding = SAML2Constants.HTTP_REDIRECT;
        if (request.getMethod().equals("POST")) {
            binding = SAML2Constants.HTTP_POST;
        }
        // Read the local metadata of the SP that made the request
        SPSSOConfigElement spEntityCfg = sm.getSPSSOConfig(realm, authnRequest.getIssuer().getValue());
        Map spConfigAttrsMap = null;
        if (spEntityCfg != null) {
            spConfigAttrsMap = SAML2MetaUtils.getAttributes(spEntityCfg);
        }
        // Check if the local configuration of the remote SP wants to use
        // the Introduction Cookie
        Boolean isIntroductionForProxyingEnabled = false;
        String useIntroductionForProxying = SPSSOFederate.getParameter(spConfigAttrsMap, SAML2Constants.USE_INTRODUCTION_FOR_IDP_PROXY);
        if (useIntroductionForProxying != null)
            isIntroductionForProxyingEnabled = useIntroductionForProxying.equalsIgnoreCase("true");
        // Check if the local configuration of the remote SP wants to use
        // the IDP Finder
        Boolean isIdPFinderEnabled = false;
        String idpFinderEnabled = SPSSOFederate.getParameter(spConfigAttrsMap, IDP_FINDER_ENABLED_IN_SP);
        if (idpFinderEnabled != null)
            isIdPFinderEnabled = idpFinderEnabled.equalsIgnoreCase("true");
        String idpFinderJSP = getIDPFinderJSP(realm, hostProviderID);
        // providerIDs will contain the list of IdPs to return from this method
        List providerIDs = new ArrayList();
        // extended metadata
        if (!isIntroductionForProxyingEnabled && !isIdPFinderEnabled && !isIdpFinderForAllSPsEnabled) {
            debugMessage(methodName, " idpFinder wil use the static list of the SP");
            List<String> proxyIDPs = null;
            if (spConfigAttrsMap != null && !spConfigAttrsMap.isEmpty()) {
                proxyIDPs = (List<String>) spConfigAttrsMap.get(SAML2Constants.IDP_PROXY_LIST);
            }
            debugMessage(methodName, " List from the configuration: " + proxyIDPs);
            if (proxyIDPs == null || proxyIDPs.isEmpty()) {
                SAML2Utils.debug.error("SAML2IDPProxyImpl.getPrefferedIDP:" + "Preferred IDPs are null.");
                return null;
            }
            // give the user the chance to select one interactively
            if (proxyIDPs.size() > 1) {
                String idpListSt = selectIDPBasedOnLOA(proxyIDPs, realm, authnRequest);
                // Construct the IDPFinder URL to redirect to
                String idpFinder = getRedirect(request, idpFinderJSP);
                // Generate the requestID
                String requestID = SAML2Utils.generateID();
                // Store the important stuff and the session parameters so the
                // idpFinderImplemenatation can read them and process them
                storeSessionParamsAndCache(request, idpListSt, authnRequest, hostProviderID, realm, requestID);
                debugMessage(methodName, ": Redirect url = " + idpFinder);
                response.sendRedirect(idpFinder);
                // return something different than null
                providerIDs.add(requestID);
                debugMessage(methodName, " Redirected successfully");
                return providerIDs;
            }
            providerIDs.add(proxyIDPs.iterator().next());
            return providerIDs;
        }
        // and it does not want to use the introduction cookie
        if (!isIntroductionForProxyingEnabled && (isIdPFinderEnabled || isIdpFinderForAllSPsEnabled)) {
            debugMessage(methodName, "SP wants to use IdP Finder");
            String idpListSt = idpList(authnRequest, realm);
            if (!idpListSt.trim().isEmpty()) {
                // Construct the IDPFinder URL to redirect to
                String idpFinder = getRedirect(request, idpFinderJSP);
                // Generate the requestID
                String requestID = SAML2Utils.generateID();
                // Store the important stuff and the session parameters so the
                // idpFinderImplemenatation can read them and process them
                storeSessionParamsAndCache(request, idpListSt, authnRequest, hostProviderID, realm, requestID);
                debugMessage(methodName, ": Redirect url = " + idpFinder);
                response.sendRedirect(idpFinder);
                // return something different than null
                providerIDs.add(requestID);
                debugMessage(methodName, " Redirected successfully");
                return providerIDs;
            } else {
                return null;
            }
        } else {
            // IDP Proxy with introduction cookie
            List cotList = (List) spConfigAttrsMap.get("cotlist");
            String cotListStr = (String) cotList.iterator().next();
            CircleOfTrustManager cotManager = new CircleOfTrustManager();
            CircleOfTrustDescriptor cotDesc = cotManager.getCircleOfTrust(realm, cotListStr);
            String readerURL = cotDesc.getSAML2ReaderServiceURL();
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "SAMLv2 idp" + "discovery reader URL = " + readerURL);
            }
            if (readerURL != null && (!readerURL.equals(""))) {
                String rID = SAML2Utils.generateID();
                String redirectURL = SAML2Utils.getRedirectURL(readerURL, rID, request);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.error(classMethod + "Redirect url = " + redirectURL);
                }
                if (redirectURL != null) {
                    response.sendRedirect(redirectURL);
                    Map aMap = new HashMap();
                    SPCache.reqParamHash.put(rID, aMap);
                    providerIDs.add(rID);
                    return providerIDs;
                }
            }
        }
        return null;
    } catch (SAML2MetaException ex) {
        SAML2Utils.debug.error(classMethod + "meta Exception in retrieving the preferred IDP", ex);
        return null;
    } catch (COTException sme) {
        SAML2Utils.debug.error(classMethod + "Error retreiving COT ", sme);
        return null;
    } catch (Exception e) {
        SAML2Utils.debug.error(classMethod + "Exception in retrieving the preferred IDP", e);
        return null;
    }
}
Also used : CircleOfTrustManager(com.sun.identity.cot.CircleOfTrustManager) HashMap(java.util.HashMap) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) ArrayList(java.util.ArrayList) CircleOfTrustDescriptor(com.sun.identity.cot.CircleOfTrustDescriptor) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) COTException(com.sun.identity.cot.COTException) COTException(com.sun.identity.cot.COTException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ArrayList(java.util.ArrayList) List(java.util.List) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 38 with AuthnRequest

use of com.sun.identity.saml2.protocol.AuthnRequest in project OpenAM by OpenRock.

the class SAML2IDPProxyFRImpl method selectIDPBasedOnAuthContext.

private String selectIDPBasedOnAuthContext(List idpList, String realm, AuthnRequest authnRequest) {
    String classMethod = "selectIdPBasedOnLOA";
    EntityDescriptorElement idpDesc = null;
    Set authnRequestContextSet = null;
    String idps = "";
    try {
        List listOfAuthnContexts = authnRequest.getRequestedAuthnContext().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);
                List supportedAuthnContextsbyIDP = getSupportedAuthnContextsByIDP(realm, idp);
                if (supportedAuthnContextsbyIDP != null) {
                    debugMessage(classMethod, "Standard Authn Contexts found for idp: " + idp);
                    Set idpContextSet = trimmedListToSet(supportedAuthnContextsbyIDP);
                    debugMessage(classMethod, "idpContextSet = " + idpContextSet);
                    idpContextSet.retainAll(authnRequestContextSet);
                    if (idpContextSet != null && !idpContextSet.isEmpty()) {
                        idps = idp + " " + idps;
                        debugMessage(classMethod, "Standard Authn Contexts found for idp " + idp + ": " + idpContextSet);
                    }
                } else {
                    debugMessage(classMethod, "The IdP" + idp + " has no standard authentication" + " contexts configured");
                }
            }
        }
    } catch (Exception me) {
        SAML2Utils.debug.error(classMethod + "Error when trying to get the idp's by standard Authn Context: " + me);
    }
    debugMessage(classMethod, " IDPList returns: " + idps);
    return idps.trim();
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) 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) HashSet(java.util.HashSet)

Example 39 with AuthnRequest

use of com.sun.identity.saml2.protocol.AuthnRequest 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)

Example 40 with AuthnRequest

use of com.sun.identity.saml2.protocol.AuthnRequest in project OpenAM by OpenRock.

the class IDPSSOUtil method redirectAuthentication.

/**
     * Redirects to authenticate service
     *
     * @param request     the <code>HttpServletRequest</code> object
     * @param response    the <code>HttpServletResponse</code> object
     * @param authnReq    the <code>AuthnRequest</code> object
     * @param reqID       the <code>AuthnRequest ID</code>
     * @param realm       the realm name of the identity provider
     * @param idpEntityID the entity id of the identity provider
     * @param spEntityID  the entity id of the service provider
     */
static void redirectAuthentication(HttpServletRequest request, HttpServletResponse response, AuthnRequest authnReq, String reqID, String realm, String idpEntityID, String spEntityID) throws SAML2Exception, IOException {
    String classMethod = "IDPSSOUtil.redirectAuthentication: ";
    // get the authentication service url 
    StringBuffer newURL = new StringBuffer(IDPSSOUtil.getAuthenticationServiceURL(realm, idpEntityID, request));
    // Pass spEntityID to IdP Auth Module
    if (spEntityID != null) {
        if (newURL.indexOf("?") == -1) {
            newURL.append("?");
        } else {
            newURL.append("&");
        }
        newURL.append(SAML2Constants.SPENTITYID);
        newURL.append("=");
        newURL.append(URLEncDec.encode(spEntityID));
    }
    // find out the authentication method, e.g. module=LDAP, from
    // authn context mapping 
    IDPAuthnContextMapper idpAuthnContextMapper = getIDPAuthnContextMapper(realm, idpEntityID);
    IDPAuthnContextInfo info = idpAuthnContextMapper.getIDPAuthnContextInfo(authnReq, idpEntityID, realm);
    Set authnTypeAndValues = info.getAuthnTypeAndValues();
    if ((authnTypeAndValues != null) && (!authnTypeAndValues.isEmpty())) {
        Iterator iter = authnTypeAndValues.iterator();
        StringBuffer authSB = new StringBuffer((String) iter.next());
        while (iter.hasNext()) {
            authSB.append("&");
            authSB.append((String) iter.next());
        }
        if (newURL.indexOf("?") == -1) {
            newURL.append("?");
        } else {
            newURL.append("&");
        }
        newURL.append(authSB.toString());
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "authString=" + authSB.toString());
        }
    }
    if (newURL.indexOf("?") == -1) {
        newURL.append("?goto=");
    } else {
        newURL.append("&goto=");
    }
    String gotoURL = request.getRequestURL().toString();
    String gotoQuery = request.getQueryString();
    //to the login interface for authentication.
    if (gotoQuery != null) {
        gotoURL += "?" + gotoQuery + "&" + REDIRECTED_TRUE;
    } else {
        gotoURL += "?" + REDIRECTED_TRUE;
    }
    if (reqID != null) {
        gotoURL += "&ReqID=" + reqID;
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "gotoURL=" + gotoURL);
    }
    newURL.append(URLEncDec.encode(gotoURL));
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "New URL for authentication: " + newURL.toString());
    }
    // TODO: here we should check if the new URL is one
    //       the same web container, if yes, forward,
    //       if not, redirect
    response.sendRedirect(newURL.toString());
    return;
}
Also used : IDPAuthnContextInfo(com.sun.identity.saml2.plugins.IDPAuthnContextInfo) IDPAuthnContextMapper(com.sun.identity.saml2.plugins.IDPAuthnContextMapper) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Iterator(java.util.Iterator)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)27 List (java.util.List)18 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)15 ArrayList (java.util.ArrayList)15 AuthnRequest (com.sun.identity.saml2.protocol.AuthnRequest)14 Map (java.util.Map)13 SessionException (com.sun.identity.plugin.session.SessionException)12 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)10 IOException (java.io.IOException)10 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)10 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)9 Date (java.util.Date)8 HashMap (java.util.HashMap)8 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)7 SAML2ServiceProviderAdapter (com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter)7 Iterator (java.util.Iterator)7 Issuer (com.sun.identity.saml2.assertion.Issuer)6 Assertion (com.sun.identity.saml2.assertion.Assertion)5 IDPList (com.sun.identity.saml2.protocol.IDPList)5 Response (com.sun.identity.saml2.protocol.Response)5