Search in sources :

Example 6 with FSAuthnRequest

use of com.sun.identity.federation.message.FSAuthnRequest in project OpenAM by OpenRock.

the class FSLoginHelper method createAuthnRequest.

/**
     * Returns a Map of headers,lrurl/responsedata.
     * @param headers Map of headers
     * @param LRURL relay state url
     * @param authLevel authentication level
     * @param metaAlias meta alias of hosted provider
     * @param remoteEntityID remote provider's entity ID
     * @param isFedCookiePresent if fed cookie present or not
     * @return Map of headers and lrurl/responedata
     * @exception FSLoginHelperException if error occurrs
     */
public Map createAuthnRequest(Map headers, String LRURL, String authLevel, String metaAlias, String remoteEntityID, boolean isFedCookiePresent) throws FSLoginHelperException {
    Map retHeaderMap = new HashMap();
    setMetaInfo(metaAlias, authLevel);
    FSUtils.debug.message("FSLoginHelper.createAuthnRequest(): called");
    FSAuthnRequest authnRequest = null;
    if (remoteEntityID != null) {
        authnRequest = getAuthnReq(headers, LRURL, true);
    } else {
        authnRequest = getAuthnReq(headers, LRURL, false);
    }
    if (authnRequest == null) {
        FSUtils.debug.error("FSLoginHelper.createAuthnRequest()::AuthnRequest is null");
        String redirectURL = errorPage + "&" + IFSConstants.FEDERROR + "=" + URLEncDec.encode("Unable to create AuthnRequest") + "&" + IFSConstants.FEDREMARK + "=" + URLEncDec.encode("Please check your Federation Configuration.");
        return createMap(redirectURL, null, retHeaderMap);
    }
    String requestID = authnRequest.getRequestID();
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSLoginHelper.createAuthnRequest()::RequestID: " + requestID);
    }
    FSSessionManager sessMngr = FSSessionManager.getInstance(metaAlias);
    sessMngr.setAuthnRequest(requestID, authnRequest);
    sessMngr.setIDPEntityID(requestID, remoteEntityID);
    String redirectURL = null;
    //check if dontgotothird level domain flag is off is yes
    //if yes then get one provider and and send to intersiteurl
    //else send to third level domain for provider id
    //also check if there is a single idp if yes go to intersite transfer 
    //with providerid
    boolean isSingleIDP = true;
    boolean isSSO = false;
    Set idpSet = getIDPs(metaAlias);
    if (remoteEntityID == null) {
        isSSO = true;
    }
    if (idpSet.size() > 1) {
        isSingleIDP = false;
    }
    //*****************
    if (isLECPProfile(headers)) {
        FSUtils.debug.message("FSLoginHelper.createAuthnRequest():LECP Request Identified");
        retHeaderMap.put("content-type", IFSConstants.LECP_CONTENT_TYPE_HEADER);
        String responseData = null;
        try {
            FSAuthnRequestEnvelope authnRequestEnvelope = null;
            boolean isPassive = false;
            FSIDPList idpList = null;
            //get IDPList from directory
            String assertionConsumerURL = FSServiceUtils.getAssertionConsumerServiceURL(hostDescriptor, null);
            List idpEntryList = null;
            String idpID = null;
            String idpName = null;
            String idpLocation = null;
            Iterator iter = idpSet.iterator();
            while (iter.hasNext()) {
                idpID = (String) iter.next();
                if (idpID != null) {
                    IDPDescriptorType idpDescr = metaManager.getIDPDescriptor(realm, idpID);
                    idpLocation = idpDescr.getSingleSignOnServiceURL();
                    if (idpEntryList == null) {
                        idpEntryList = new ArrayList();
                    }
                    idpEntryList.add(new IDPEntry(idpID, idpID, idpLocation));
                }
            }
            IDPEntries idpEntries = new IDPEntries(idpEntryList);
            idpList = new FSIDPList(idpEntries, null);
            int minorVersion = FSServiceUtils.getMinorVersion(hostDescriptor.getProtocolSupportEnumeration());
            idpList.setMinorVersion(minorVersion);
            authnRequest.setMinorVersion(minorVersion);
            if (FSServiceUtils.isSigningOn()) {
                if (hostDescriptor.isAuthnRequestsSigned()) {
                    authnRequest.signXML(IDFFMetaUtils.getFirstAttributeValueFromConfig(hostConfig, IFSConstants.SIGNING_CERT_ALIAS));
                }
            }
            authnRequestEnvelope = new FSAuthnRequestEnvelope(authnRequest, hostEntityID, hostEntityID, assertionConsumerURL, idpList, isPassive);
            authnRequestEnvelope.setMinorVersion(minorVersion);
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSLoginHelper.createAuthnRequest: " + "AuthnRequestEnvelope: " + authnRequestEnvelope.toXMLString());
            }
            responseData = authnRequestEnvelope.toXMLString();
        // responseData = authnRequestEnvelope.toBASE64EncodedString();
        } catch (Exception e) {
            FSUtils.debug.error("FSLoginHelper.createAuthnRequest(): " + "Exception Occured: " + e.getMessage());
        }
        Map retMap = createMap(null, responseData, retHeaderMap);
        retMap.put(authnReqIDKey, requestID);
        return retMap;
    }
    //*****************
    String tldURL = getTLDURL();
    if (isSSO && tldURL != null && !isSingleIDP) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSLoginHelper:: createAuthnRequest " + "In case where isSSO true and tldURL is true and not " + "single idp. So redirecting to thirdlevel domain");
        }
        redirectURL = tldURL + "?" + IFSConstants.LRURL + "=" + URLEncDec.encode(interSiteURL + "?" + authnReqIDKey + "=" + URLEncDec.encode(requestID) + "&" + IFSConstants.META_ALIAS + "=" + metaAlias);
    } else if (isSSO && !isSingleIDP) {
        if (FSUtils.debug.messageEnabled())
            FSUtils.debug.message("FSLoginHelper:: createAuthnRequest " + " In case where isSSO true and not a single idp so have " + "show common login page");
        Map retMap = createMap(null, null, retHeaderMap);
        retMap.put(authnReqIDKey, requestID);
        return retMap;
    } else {
        boolean noIDP = false;
        if (remoteEntityID == null) {
            if (idpSet != null && idpSet.size() > 0) {
                remoteEntityID = (String) idpSet.iterator().next();
            } else {
                FSUtils.debug.error("FSLoginHelper:: no idps found in config." + " Cannot proceed.");
                redirectURL = errorPage + "&" + IFSConstants.FEDERROR + "=" + URLEncDec.encode("No IDPs Found in Configuration.") + "&" + IFSConstants.FEDREMARK + "=" + URLEncDec.encode("Please configure you Federation Services for an IDP.");
                noIDP = true;
            }
        }
        if (!noIDP) {
            String succintID = FSUtils.generateSourceID(remoteEntityID);
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSLoginHelper:: createAuthnRequest " + " Redirecting to intersiteTransfer URL " + interSiteURL + " with providerID and Base64 encoded SuccintID. " + remoteEntityID + "---" + succintID);
            }
            //check for presence of federate cookie
            if (!isFedCookiePresent) {
                if (actionOnNoFedCookie.equals(IFSConstants.COMMON_LOGIN)) {
                    Map retMap = createMap(null, null, retHeaderMap);
                    retMap.put(authnReqIDKey, requestID);
                    return retMap;
                } else if (actionOnNoFedCookie.equals(IFSConstants.ACTIVE)) {
                    changeToPassiveAuthnRequest(requestID, false, metaAlias);
                } else {
                    changeToPassiveAuthnRequest(requestID, true, metaAlias);
                }
            }
            String providerID = FSUtils.stringToBase64(succintID);
            redirectURL = interSiteURL + "?" + authnReqIDKey + "=" + URLEncDec.encode(requestID) + "&" + providerIDKey + "=" + URLEncDec.encode(providerID) + "&" + IFSConstants.META_ALIAS + "=" + metaAlias;
        }
    }
    /**
         * If this flag is set via the query param, we will always make
         * a passive call to the IDP.
         */
    if (isPassiveQuery) {
        changeToPassiveAuthnRequest(requestID, true, metaAlias);
    }
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSLoginHelper.createAuthnRequest()::" + "redirectURL : " + redirectURL);
    }
    if (isWMLProfile(headers)) {
        retHeaderMap.put("content-type", "text/vnd.wap.wml");
    } else {
        retHeaderMap.put("content-type", "text/html");
    }
    Map retMap = createMap(redirectURL, null, retHeaderMap);
    retMap.put(authnReqIDKey, requestID);
    return retMap;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) FSAuthnRequestEnvelope(com.sun.identity.federation.message.FSAuthnRequestEnvelope) ArrayList(java.util.ArrayList) IDPEntries(com.sun.identity.federation.message.common.IDPEntries) COTException(com.sun.identity.cot.COTException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) FSIDPList(com.sun.identity.federation.message.FSIDPList) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) FSIDPList(com.sun.identity.federation.message.FSIDPList) IDPEntry(com.sun.identity.federation.message.common.IDPEntry) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with FSAuthnRequest

use of com.sun.identity.federation.message.FSAuthnRequest in project OpenAM by OpenRock.

the class FSSOAPReceiver method onMessage.

/**
     * Process the request.
     * @param request http request object
     * @param response http response object
     * @param message received soap message
     */
public void onMessage(HttpServletRequest request, HttpServletResponse response, SOAPMessage message) {
    FSUtils.debug.message("FSSOAPReceiver.onMessage: Called");
    try {
        Element elt = soapService.parseSOAPMessage(message);
        if (elt == null) {
            FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request. Invalid SOAPMessage");
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
            return;
        }
        String eltTagName = (elt.getTagName().trim());
        String ns = elt.getNamespaceURI().trim();
        String nodeName = elt.getLocalName().trim();
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "tagName: " + eltTagName + " namespaceUri: " + ns + " localName: " + nodeName);
        }
        //check for saml:Request
        if (nodeName.equalsIgnoreCase("Request") && ns.equalsIgnoreCase(IFSConstants.PROTOCOL_NAMESPACE_URI)) {
            SOAPMessage retMessage = null;
            try {
                FSSAMLRequest samlRequest = new FSSAMLRequest(elt);
                IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                if (metaManager == null) {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "could not create meta instance");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
                String metaAlias = FSServiceUtils.getMetaAlias(request);
                String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
                String hostedEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
                IDPDescriptorType hostedDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                BaseConfigType hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                FSServiceManager sm = FSServiceManager.getInstance();
                FSSSOBrowserArtifactProfileHandler handler = (FSSSOBrowserArtifactProfileHandler) sm.getBrowserArtifactSSOAndFedHandler(request, response, samlRequest);
                handler.setSOAPMessage(message);
                handler.setSAMLRequestElement(elt);
                handler.setHostedEntityId(hostedEntityId);
                handler.setHostedDescriptor(hostedDesc);
                handler.setHostedDescriptorConfig(hostedConfig);
                handler.setMetaAlias(metaAlias);
                handler.setRealm(realm);
                FSResponse samlResponse = handler.processSAMLRequest(samlRequest);
                if (samlResponse != null) {
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "SAML Response created: " + samlResponse.toXMLString());
                    }
                } else {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "SAML Response is null");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
                // introduce id attribute for Assertion bind in 
                // SOAPEnvelope and sign
                retMessage = soapService.bind(((FSResponse) samlResponse).toXMLString(true, true));
                if (FSServiceUtils.isSigningOn()) {
                    List assList = samlResponse.getAssertion();
                    Iterator iter = assList.iterator();
                    while (iter.hasNext()) {
                        FSAssertion assertion = (FSAssertion) iter.next();
                        String id = assertion.getID();
                        Document doc = (Document) FSServiceUtils.createSOAPDOM(retMessage);
                        String certAlias = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS);
                        if (certAlias == null) {
                            if (FSUtils.debug.messageEnabled()) {
                                FSUtils.debug.message("SOAPReceiver.onMessage: couldn't " + "obtain this site's cert alias.");
                            }
                            throw new SAMLResponderException(FSUtils.bundle.getString("cannotFindCertAlias"));
                        }
                        XMLSignatureManager manager = XMLSignatureManager.getInstance();
                        int minorVersion = assertion.getMinorVersion();
                        if (minorVersion == IFSConstants.FF_11_ASSERTION_MINOR_VERSION) {
                            manager.signXML(doc, certAlias, SystemConfigurationUtil.getProperty(SAMLConstants.XMLSIG_ALGORITHM), IFSConstants.ID, id, false);
                        } else if (minorVersion == IFSConstants.FF_12_POST_ASSERTION_MINOR_VERSION || minorVersion == IFSConstants.FF_12_ART_ASSERTION_MINOR_VERSION) {
                            manager.signXML(doc, certAlias, SystemConfigurationUtil.getProperty(SAMLConstants.XMLSIG_ALGORITHM), IFSConstants.ASSERTION_ID, assertion.getAssertionID(), false);
                        } else {
                            FSUtils.debug.error("invalid minor version.");
                        }
                        retMessage = FSServiceUtils.convertDOMToSOAP(doc);
                    }
                }
                if (retMessage == null) {
                    FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request");
                    response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            } catch (SAMLException se) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request:", se);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            } catch (IDFFMetaException me) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing saml:Request:", me);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
            returnSOAPMessage(retMessage, response);
            return;
        }
        if (nodeName.equalsIgnoreCase("AuthnRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            SOAPMessage retMessage = null;
            try {
                FSAuthnRequest authnRequest = new FSAuthnRequest(elt);
                handleLECPRequest(request, response, authnRequest);
                retMessage = null;
            } catch (FSException e) {
                FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing lecp AuthnRequest:", e);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
            returnSOAPMessage(retMessage, response);
            return;
        } else if (nodeName.equalsIgnoreCase("RegisterNameIdentifierRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            SOAPMessage retMessage = null;
            boolean isError = false;
            String providerAlias = null;
            ProviderDescriptorType hostedProviderDesc = null;
            BaseConfigType hostedConfig = null;
            String realm = null;
            String hostedEntityId = null;
            String hostedRole = null;
            try {
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "Handling NameRegistrationRequest");
                }
                IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                if (metaManager == null) {
                    FSUtils.debug.message("Unable to get meta manager");
                    isError = true;
                } else {
                    providerAlias = FSServiceUtils.getMetaAlias(request);
                    if (providerAlias == null || providerAlias.length() < 1) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("Unable to retrieve alias" + "Hosted Provider. Cannot process request");
                        }
                        isError = true;
                    }
                    realm = IDFFMetaUtils.getRealmByMetaAlias(providerAlias);
                    try {
                        hostedRole = metaManager.getProviderRoleByMetaAlias(providerAlias);
                        hostedEntityId = metaManager.getEntityIDByMetaAlias(providerAlias);
                        if (hostedRole != null && hostedRole.equals(IFSConstants.IDP)) {
                            hostedProviderDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                        } else if (hostedRole != null && hostedRole.equals(IFSConstants.SP)) {
                            hostedProviderDesc = metaManager.getSPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getSPDescriptorConfig(realm, hostedEntityId);
                        }
                        if (hostedProviderDesc == null) {
                            throw new IDFFMetaException((String) null);
                        }
                    } catch (IDFFMetaException eam) {
                        FSUtils.debug.error("Unable to find Hosted Provider. " + "Cannot process request");
                        isError = true;
                    }
                }
                if (isError || hostedProviderDesc == null) {
                    returnSOAPMessage(retMessage, response);
                    return;
                } else {
                    FSNameRegistrationResponse regisResponse = handleRegistrationRequest(elt, message, hostedProviderDesc, hostedConfig, hostedRole, realm, hostedEntityId, providerAlias, request, response);
                    if (regisResponse == null) {
                        FSUtils.debug.error("Error in creating NameRegistration Response");
                        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                        retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                    } else {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("FSSOAPReceiver.onMessage: " + "Completed creating response");
                        }
                        retMessage = soapService.bind(regisResponse.toXMLString(true, true));
                        FSUtils.debug.message("Completed bind message");
                        if (retMessage == null) {
                            FSUtils.debug.error("Error in processing NameRegistration " + "Response");
                            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                            retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                        } else {
                            if (FSServiceUtils.isSigningOn()) {
                                try {
                                    int minorVersion = regisResponse.getMinorVersion();
                                    if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
                                        retMessage = signResponse(retMessage, IFSConstants.ID, regisResponse.getID(), hostedConfig);
                                    } else if (minorVersion == IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
                                        retMessage = signResponse(retMessage, IFSConstants.RESPONSE_ID, regisResponse.getResponseID(), hostedConfig);
                                    } else {
                                        if (FSUtils.debug.messageEnabled()) {
                                            FSUtils.debug.message("invalid minor version.");
                                        }
                                    }
                                } catch (SAMLException e) {
                                    FSUtils.debug.error("FSNameRegistrationHandler:" + "sign soap Response failed", e);
                                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                                    return;
                                } catch (FSMsgException e) {
                                    FSUtils.debug.error("FSNameRegistrationHandler::" + "signRegistrationResponse failed", e);
                                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                                    return;
                                }
                            }
                        }
                    }
                }
                if (FSUtils.debug.messageEnabled()) {
                    ByteArrayOutputStream bop = null;
                    String xmlString = null;
                    bop = new ByteArrayOutputStream();
                    retMessage.writeTo(bop);
                    xmlString = bop.toString(IFSConstants.DEFAULT_ENCODING);
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("return SOAP message:" + xmlString);
                    }
                }
                returnSOAPMessage(retMessage, response);
                return;
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing Name Registration request" + se.getMessage());
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                retMessage = soapService.formSOAPError("Server", "cannotProcessRequest", null);
                returnSOAPMessage(retMessage, response);
            }
        } else if (nodeName.equalsIgnoreCase("NameIdentifierMappingRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            FSUtils.debug.message("FSSOAPReceiver:handling Name Identifier Mapping Request");
            IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
            String metaAlias = FSServiceUtils.getMetaAlias(request);
            String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
            String hostedEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
            ProviderDescriptorType hostedDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
            BaseConfigType hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
            FSNameIdentifierMappingRequest mappingRequest = new FSNameIdentifierMappingRequest(elt);
            if (FSServiceUtils.isSigningOn()) {
                String remoteEntityId = mappingRequest.getProviderID();
                ProviderDescriptorType remoteDesc = getRemoteProviderDescriptor(// it has to be idp
                IFSConstants.IDP, remoteEntityId, realm);
                if (remoteDesc == null) {
                    return;
                }
                if (verifyRequestSignature(elt, message, KeyUtil.getVerificationCert(remoteDesc, remoteEntityId, true))) {
                    if (FSUtils.debug.messageEnabled()) {
                        FSUtils.debug.message("FSSOAPReceiver: Success in verifying " + "Name Identifier Mapping Request");
                    }
                } else {
                    FSUtils.debug.error("Failed verifying Name Identifier Mapping Request");
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            }
            String targetNamespace = mappingRequest.getTargetNamespace();
            String inResponseTo = mappingRequest.getRequestID();
            Status status = new Status(new StatusCode("samlp:Success"));
            FSNameMappingHandler idpHandler = new FSNameMappingHandler(hostedEntityId, hostedDesc, hostedConfig, metaAlias);
            NameIdentifier nameIdentifier = idpHandler.getNameIdentifier(mappingRequest, targetNamespace, false);
            String enableEncryption = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.ENABLE_NAMEID_ENCRYPTION);
            if (enableEncryption != null && enableEncryption.equalsIgnoreCase("true")) {
                nameIdentifier = EncryptedNameIdentifier.getEncryptedNameIdentifier(nameIdentifier, realm, targetNamespace);
            }
            FSNameIdentifierMappingResponse mappingResponse = new FSNameIdentifierMappingResponse(hostedEntityId, inResponseTo, status, nameIdentifier);
            if (FSServiceUtils.isSigningOn()) {
                String certAlias = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS);
                mappingResponse.signXML(certAlias);
            }
            SOAPMessage retMessage = soapService.bind(mappingResponse.toXMLString(true, true));
            returnSOAPMessage(retMessage, response);
            return;
        } else if (nodeName.equalsIgnoreCase("FederationTerminationNotification") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            try {
                FSUtils.debug.message("calling FSSOAPReceiver::handleTerminationRequest");
                boolean bHandleStatus = handleTerminationRequest(elt, message, request, response);
                if (bHandleStatus) {
                    FSUtils.debug.message("Completed processing terminationRequest");
                    returnTerminationStatus(response);
                    return;
                } else {
                    FSUtils.debug.message("Failed processing terminationRequest");
                    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                    return;
                }
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing Federation Termination Request", se);
                String[] data = { IFSConstants.TERMINATION_REQUEST_PROCESSING_FAILED };
                LogUtil.error(Level.INFO, LogUtil.TERMINATION_REQUEST_PROCESSING_FAILED, data);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
        } else if (nodeName.equalsIgnoreCase("LogoutRequest") && (ns.equalsIgnoreCase(IFSConstants.libertyMessageNamespaceURI) || ns.equalsIgnoreCase(IFSConstants.FF_12_XML_NS))) {
            try {
                FSUtils.debug.message("calling FSSOAPReceiver::handleLogoutRequest");
                ProviderDescriptorType hostedProviderDesc = null;
                BaseConfigType hostedConfig = null;
                String providerAlias = null;
                String realm = null;
                String hostedEntityId = null;
                String hostedRole = null;
                try {
                    providerAlias = FSServiceUtils.getMetaAlias(request);
                    realm = IDFFMetaUtils.getRealmByMetaAlias(providerAlias);
                    IDFFMetaManager metaManager = FSUtils.getIDFFMetaManager();
                    hostedRole = metaManager.getProviderRoleByMetaAlias(providerAlias);
                    hostedEntityId = metaManager.getEntityIDByMetaAlias(providerAlias);
                    if (hostedRole != null) {
                        if (hostedRole.equalsIgnoreCase(IFSConstants.IDP)) {
                            hostedProviderDesc = metaManager.getIDPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getIDPDescriptorConfig(realm, hostedEntityId);
                        } else if (hostedRole.equalsIgnoreCase(IFSConstants.SP)) {
                            hostedProviderDesc = metaManager.getSPDescriptor(realm, hostedEntityId);
                            hostedConfig = metaManager.getSPDescriptorConfig(realm, hostedEntityId);
                        }
                    }
                } catch (Exception e) {
                    FSUtils.debug.error("FSSOAPReceiver, provider", e);
                }
                FSLogoutNotification logoutRequest = new FSLogoutNotification(elt);
                Map map = handleLogoutRequest(elt, logoutRequest, message, request, response, hostedProviderDesc, hostedConfig, providerAlias, realm, hostedEntityId, hostedRole);
                String responseID = SAMLUtils.generateID();
                String inResponseTo = logoutRequest.getRequestID();
                String relayState = logoutRequest.getRelayState();
                FSLogoutResponse resp = null;
                boolean statusSuccess = false;
                SOAPMessage retSoapMessage = null;
                if (map == null) {
                    StatusCode statusCode = new StatusCode(IFSConstants.SAML_RESPONDER);
                    Status status = new Status(statusCode);
                    resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                } else {
                    retSoapMessage = (SOAPMessage) map.get(MESSAGE);
                    SOAPPart sp = retSoapMessage.getSOAPPart();
                    SOAPEnvelope se = sp.getEnvelope();
                    SOAPBody sb = se.getBody();
                    if (sb.hasFault()) {
                        StatusCode secondLevelstatusCode = new StatusCode(IFSConstants.SAML_UNSUPPORTED);
                        StatusCode statusCode = new StatusCode(IFSConstants.SAML_RESPONDER, secondLevelstatusCode);
                        Status status = new Status(statusCode);
                        resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                    } else {
                        StatusCode statusCode = new StatusCode(IFSConstants.SAML_SUCCESS);
                        Status status = new Status(statusCode);
                        resp = new FSLogoutResponse(responseID, inResponseTo, status, hostedEntityId, relayState);
                        statusSuccess = true;
                    }
                }
                resp.setID(IFSConstants.LOGOUTID);
                resp.setMinorVersion(logoutRequest.getMinorVersion());
                retSoapMessage = soapService.bind(resp.toXMLString(true, true));
                // Call SP Adapter postSingleLogoutSuccess for IDP/SOAP
                if (hostedRole != null && hostedRole.equalsIgnoreCase(IFSConstants.SP) && statusSuccess) {
                    FederationSPAdapter spAdapter = FSServiceUtils.getSPAdapter(hostedEntityId, hostedConfig);
                    if (spAdapter != null) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("FSSOAPReceiver, " + "call postSingleLogoutSuccess, IDP/SOAP");
                        }
                        try {
                            spAdapter.postSingleLogoutSuccess(hostedEntityId, request, response, (String) map.get(USERID), logoutRequest, resp, IFSConstants.LOGOUT_IDP_SOAP_PROFILE);
                        } catch (Exception e) {
                            // ignore adapter exception
                            FSUtils.debug.error("postSingleLogoutSuccess." + "IDP/SOAP", e);
                        }
                    }
                }
                if (FSServiceUtils.isSigningOn()) {
                    try {
                        int minorVersion = resp.getMinorVersion();
                        if (minorVersion == IFSConstants.FF_11_PROTOCOL_MINOR_VERSION) {
                            retSoapMessage = signResponse(retSoapMessage, IFSConstants.ID, resp.getID(), hostedConfig);
                        } else if (minorVersion == IFSConstants.FF_12_PROTOCOL_MINOR_VERSION) {
                            retSoapMessage = signResponse(retSoapMessage, IFSConstants.RESPONSE_ID, resp.getResponseID(), hostedConfig);
                        } else {
                            FSUtils.debug.error("invalid minor version.");
                        }
                    } catch (SAMLException e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("LogoutResponse failed", e);
                        }
                        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                        return;
                    } catch (FSMsgException e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("LogoutResponse failed", e);
                        }
                        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                        return;
                    } catch (Exception e) {
                        if (FSUtils.debug.messageEnabled()) {
                            FSUtils.debug.message("Logout exception:", e);
                        }
                    }
                }
                returnSOAPMessage(retSoapMessage, response);
                return;
            } catch (Exception se) {
                FSUtils.debug.error("Error in processing logout Request", se);
                String[] data = { FSUtils.bundle.getString(IFSConstants.LOGOUT_REQUEST_PROCESSING_FAILED) };
                LogUtil.error(Level.INFO, LogUtil.LOGOUT_REQUEST_PROCESSING_FAILED, data);
                returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
                return;
            }
        }
    //check for other Liberty msgs should go here
    } catch (Exception e) {
        FSUtils.debug.error("FSSOAPReceiver.onMessage: " + "Error in processing Request: Exception occured: ", e);
        response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        java.io.ByteArrayOutputStream strm = new java.io.ByteArrayOutputStream();
        e.printStackTrace(new java.io.PrintStream(strm));
        FSUtils.debug.error(strm.toString());
        returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
        return;
    }
    returnSOAPMessage(soapService.formSOAPError("Server", "cannotProcessRequest", null), response);
    return;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) NameIdentifier(com.sun.identity.saml.assertion.NameIdentifier) EncryptedNameIdentifier(com.sun.identity.federation.message.common.EncryptedNameIdentifier) Element(org.w3c.dom.Element) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) FSLogoutNotification(com.sun.identity.federation.message.FSLogoutNotification) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) FSAssertion(com.sun.identity.federation.message.FSAssertion) Iterator(java.util.Iterator) FSException(com.sun.identity.federation.common.FSException) SOAPPart(javax.xml.soap.SOAPPart) List(java.util.List) FSSAMLRequest(com.sun.identity.federation.message.FSSAMLRequest) FederationSPAdapter(com.sun.identity.federation.plugins.FederationSPAdapter) FSLogoutStatus(com.sun.identity.federation.services.logout.FSLogoutStatus) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) ProviderDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.ProviderDescriptorType) XMLSignatureManager(com.sun.identity.saml.xmlsig.XMLSignatureManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FSNameIdentifierMappingResponse(com.sun.identity.federation.message.FSNameIdentifierMappingResponse) FSLogoutResponse(com.sun.identity.federation.message.FSLogoutResponse) SOAPException(javax.xml.soap.SOAPException) SystemConfigurationException(com.sun.identity.common.SystemConfigurationException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) FSException(com.sun.identity.federation.common.FSException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) SOAPBody(javax.xml.soap.SOAPBody) FSSSOBrowserArtifactProfileHandler(com.sun.identity.federation.services.fednsso.FSSSOBrowserArtifactProfileHandler) FSNameMappingHandler(com.sun.identity.federation.services.namemapping.FSNameMappingHandler) IDFFMetaManager(com.sun.identity.federation.meta.IDFFMetaManager) FSResponse(com.sun.identity.federation.message.FSResponse) FSNameRegistrationResponse(com.sun.identity.federation.message.FSNameRegistrationResponse) FSNameIdentifierMappingRequest(com.sun.identity.federation.message.FSNameIdentifierMappingRequest) Map(java.util.Map) HashMap(java.util.HashMap)

Example 8 with FSAuthnRequest

use of com.sun.identity.federation.message.FSAuthnRequest in project OpenAM by OpenRock.

the class FSBrowserArtifactConsumerHandler method processSAMLResponse.

private void processSAMLResponse(FSResponse samlResponse) {
    FSUtils.debug.message("FSBrowserArtifactConsumerHandler.processSAMLResponse: Called");
    String baseURL = FSServiceUtils.getBaseURL(request);
    String framedPageURL = FSServiceUtils.getCommonLoginPageURL(hostMetaAlias, relayState, null, request, baseURL);
    try {
        if (samlResponse == null) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: null input " + FSUtils.bundle.getString("missingResponse"));
            String[] data = { FSUtils.bundle.getString("missingResponse") };
            LogUtil.error(Level.INFO, LogUtil.MISSING_RESPONSE, data);
            FSUtils.forwardRequest(request, response, framedPageURL);
            return;
        }
        FederationSPAdapter spAdapter = FSServiceUtils.getSPAdapter(hostEntityId, hostConfig);
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: Received " + samlResponse.toXMLString());
        }
        boolean valid = verifyResponseStatus(samlResponse);
        if (!valid) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: verify Status failed " + FSUtils.bundle.getString("invalidResponse"));
            String[] data = { samlResponse.toXMLString() };
            LogUtil.error(Level.INFO, LogUtil.INVALID_RESPONSE, data);
            if (spAdapter == null || !spAdapter.postSSOFederationFailure(hostEntityId, request, response, authnRequest, null, samlResponse, FederationSPAdapter.INVALID_RESPONSE)) {
                FSUtils.forwardRequest(request, response, framedPageURL);
            }
            return;
        }
        // check Assertion
        List assertions = samlResponse.getAssertion();
        if ((assertions == null) || !(assertions.size() > 0)) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse" + FSUtils.bundle.getString("invalidResponse") + ": No assertion found inside the AuthnResponse");
            String[] data = { samlResponse.toXMLString() };
            LogUtil.error(Level.INFO, LogUtil.INVALID_RESPONSE, data);
            FSUtils.forwardRequest(request, response, framedPageURL);
            return;
        }
        Iterator iter = assertions.iterator();
        FSAssertion assertion = (FSAssertion) iter.next();
        FSAuthnRequest authnRequestRef = getInResponseToRequest(assertion.getInResponseTo());
        if (authnRequestRef == null) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: " + FSUtils.bundle.getString("invalidResponse") + ": Assertion does not correspond to any AuthnRequest");
            String[] data = { samlResponse.toXMLString() };
            LogUtil.error(Level.INFO, LogUtil.INVALID_RESPONSE, data);
            FSUtils.forwardRequest(request, response, framedPageURL);
            return;
        }
        this.authnRequest = authnRequestRef;
        this.relayState = authnRequest.getRelayState();
        if ((this.relayState == null) || (this.relayState.trim().length() == 0)) {
            this.relayState = IDFFMetaUtils.getFirstAttributeValueFromConfig(hostConfig, IFSConstants.PROVIDER_HOME_PAGE_URL);
            if ((this.relayState == null) || (this.relayState.trim().length() == 0)) {
                this.relayState = baseURL + IFSConstants.SP_DEFAULT_RELAY_STATE;
            }
        }
        this.doFederate = authnRequest.getFederate();
        this.nameIDPolicy = authnRequest.getNameIDPolicy();
        // Call SP preSSOFederationProcess for Artifact case
        if (spAdapter != null) {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSBrowserArtifactConsumerHandler, " + "Artifact, Invoke spAdapter.preSSOFederationProcess");
            }
            try {
                spAdapter.preSSOFederationProcess(hostEntityId, request, response, authnRequest, null, (FSResponse) samlResponse);
            } catch (Exception e) {
                // log run time exception in Adapter
                // implementation, continue
                FSUtils.debug.error("FSAssertionArtifactHandler" + " SPAdapter.preSSOFederationSuccess", e);
            }
        }
        framedPageURL = FSServiceUtils.getCommonLoginPageURL(hostMetaAlias, authnRequest.getRelayState(), null, request, baseURL);
        String idpEntityIdRef = getProvider(assertion.getInResponseTo());
        if ((idpEntityIdRef == null) || !(idpEntityIdRef.equals(idpEntityId))) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: " + FSUtils.bundle.getString("invalidAssertion") + ": Assertion does not correspond to any IDP");
            String[] data = { FSUtils.bundle.getString("invalidAssertion") };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ASSERTION, data);
            FSUtils.forwardRequest(request, response, framedPageURL);
            return;
        }
        FSSubject validSubject = (FSSubject) validateAssertions(assertions);
        if (validSubject == null) {
            FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: validateAssertions failed: " + FSUtils.bundle.getString("invalidAssertion"));
            String[] data = { FSUtils.bundle.getString("invalidAssertion") };
            LogUtil.error(Level.INFO, LogUtil.INVALID_ASSERTION, data);
            if (spAdapter == null || !spAdapter.postSSOFederationFailure(hostEntityId, request, response, authnRequest, null, samlResponse, FederationSPAdapter.INVALID_RESPONSE)) {
                FSUtils.forwardRequest(request, response, framedPageURL);
            }
            return;
        }
        if (doFederate) {
            NameIdentifier ni = validSubject.getIDPProvidedNameIdentifier();
            if (ni == null) {
                ni = validSubject.getNameIdentifier();
            }
            if (ni != null) {
                int returnCode = doAccountFederation(ni);
                if (returnCode == FederationSPAdapter.SUCCESS) {
                    // remove it from session manager table
                    FSSessionManager sessionManager = FSSessionManager.getInstance(hostMetaAlias);
                    sessionManager.removeAuthnRequest(assertion.getInResponseTo());
                    return;
                } else {
                    FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: " + FSUtils.bundle.getString("AccountFederationFailed"));
                    String[] data = { FSUtils.bundle.getString("AccountFederationFailed") };
                    LogUtil.error(Level.INFO, LogUtil.ACCOUNT_FEDERATION_FAILED, data);
                    if (spAdapter == null || !spAdapter.postSSOFederationFailure(hostEntityId, request, response, authnRequest, authnResponse, samlResponse, returnCode)) {
                        FSUtils.forwardRequest(request, response, framedPageURL);
                    }
                }
            } else {
                FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: Single Sign-On failed. " + "NameIdentifier of the subject is null: ");
                String[] data = { FSUtils.bundle.getString("SingleSignOnFailed") };
                LogUtil.error(Level.INFO, LogUtil.SINGLE_SIGNON_FAILED, data);
                throw new FSException("missingNIofSubject", null);
            }
        } else {
            // remove it from session manager table
            FSSessionManager sessionManager = FSSessionManager.getInstance(hostMetaAlias);
            sessionManager.removeAuthnRequest(assertion.getInResponseTo());
            NameIdentifier niIdp = validSubject.getIDPProvidedNameIdentifier();
            NameIdentifier ni = validSubject.getNameIdentifier();
            if (niIdp == null) {
                niIdp = ni;
            }
            if ((niIdp == null) || (ni == null)) {
                String[] data = { FSUtils.bundle.getString("invalidResponse") };
                LogUtil.error(Level.INFO, LogUtil.INVALID_RESPONSE, data);
                FSUtils.forwardRequest(request, response, framedPageURL);
                return;
            }
            String idpHandle = niIdp.getName();
            String spHandle = ni.getName();
            int handleType;
            if ((idpHandle == null) || (spHandle == null)) {
                String[] data = { FSUtils.bundle.getString("invalidResponse") };
                LogUtil.error(Level.INFO, LogUtil.INVALID_RESPONSE, data);
                FSUtils.forwardRequest(request, response, framedPageURL);
                return;
            }
            if (idpHandle.equals(spHandle)) {
                ni = niIdp;
                handleType = IFSConstants.REMOTE_OPAQUE_HANDLE;
            } else {
                handleType = IFSConstants.LOCAL_OPAQUE_HANDLE;
            }
            if (ni != null) {
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: NameIdentifier=" + ni.getName() + " securityDomain=" + ni.getNameQualifier());
                }
                Map env = new HashMap();
                env.put(IFSConstants.FS_USER_PROVIDER_ENV_FSRESPONSE_KEY, samlResponse);
                int returnCode = doSingleSignOn(ni, handleType, niIdp, env);
                if (returnCode == FederationSPAdapter.SUCCESS) {
                    String requestID = assertion.getInResponseTo();
                    if (isIDPProxyEnabled(requestID)) {
                        sendProxyResponse(requestID);
                        return;
                    }
                    String[] data = { this.relayState };
                    LogUtil.access(Level.INFO, LogUtil.ACCESS_GRANTED_REDIRECT_TO, data, ssoToken);
                    // Call SP Adapter
                    if (spAdapter != null) {
                        FSUtils.debug.message("Invoke spAdapter");
                        try {
                            if (spAdapter.postSSOFederationSuccess(hostEntityId, request, response, ssoToken, authnRequest, null, samlResponse)) {
                                return;
                            }
                        } catch (Exception e) {
                            // log run time exception in Adapter
                            // implementation, continue
                            FSUtils.debug.error("FSAssertionArtifactHandler" + " SPAdapter.postSSOFederationSuccess:", e);
                        }
                    }
                    redirectToResource(this.relayState);
                    return;
                } else {
                    FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: SingleSignOnFailed, ni=" + ni.getName() + "[" + ni.getNameQualifier() + "]");
                    String[] data = { ni.getName() };
                    LogUtil.error(Level.INFO, LogUtil.SINGLE_SIGNON_FAILED, data);
                    if (spAdapter == null || !spAdapter.postSSOFederationFailure(hostEntityId, request, response, authnRequest, null, samlResponse, returnCode)) {
                        FSUtils.forwardRequest(request, response, framedPageURL);
                    }
                    return;
                }
            } else {
                FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: SingleSignOnFailed (null)");
                String[] data = { FSUtils.bundle.getString("SingleSignOnFailed") };
                LogUtil.error(Level.INFO, LogUtil.SINGLE_SIGNON_FAILED, data);
                throw new FSException("missingNIofSubject", null);
            }
        }
    } catch (Exception e) {
        FSUtils.debug.error("FSBrowserArtifactConsumerHandler." + "processSAMLResponse: Exception occured: ", e);
        return;
    }
}
Also used : FSSubject(com.sun.identity.federation.message.FSSubject) NameIdentifier(com.sun.identity.saml.assertion.NameIdentifier) HashMap(java.util.HashMap) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) SAMLResponderException(com.sun.identity.saml.common.SAMLResponderException) SAMLException(com.sun.identity.saml.common.SAMLException) FSException(com.sun.identity.federation.common.FSException) FSAssertion(com.sun.identity.federation.message.FSAssertion) Iterator(java.util.Iterator) FSException(com.sun.identity.federation.common.FSException) List(java.util.List) FSSessionManager(com.sun.identity.federation.services.FSSessionManager) FederationSPAdapter(com.sun.identity.federation.plugins.FederationSPAdapter) HashMap(java.util.HashMap) Map(java.util.Map)

Example 9 with FSAuthnRequest

use of com.sun.identity.federation.message.FSAuthnRequest in project OpenAM by OpenRock.

the class FSAssertionConsumerService method doPost.

/**
     * Handles post profile.
     * @param request <code>HttpServletRequest</code> object
     * @param response <code>HttpServletResponse</code> object
     * @exception ServletException, IOException if error occurs.
     */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    FSUtils.debug.message("FSAssertionConsumerService.doPost : called");
    Document doc = null;
    if ((request == null) || (response == null)) {
        response.sendError(response.SC_INTERNAL_SERVER_ERROR, FSUtils.bundle.getString("nullInputParameter"));
        return;
    }
    String metaAlias = FSServiceUtils.getMetaAlias(request);
    String realm = IDFFMetaUtils.getRealmByMetaAlias(metaAlias);
    String baseURL = FSServiceUtils.getBaseURL(request);
    String framedPageURL = FSServiceUtils.getCommonLoginPageURL(metaAlias, null, null, request, baseURL);
    String hostEntityId = null;
    SPDescriptorType hostDesc = null;
    BaseConfigType hostConfig = null;
    try {
        hostEntityId = metaManager.getEntityIDByMetaAlias(metaAlias);
        hostDesc = metaManager.getSPDescriptor(realm, hostEntityId);
        hostConfig = metaManager.getSPDescriptorConfig(realm, hostEntityId);
    } catch (Exception e) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Exception when obtain host meta data:", e);
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    // obtain AuthnResponse message
    String encodedAuthnResponse = request.getParameter(IFSConstants.POST_AUTHN_RESPONSE_PARAM);
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "Base64 encoded AuthnResponse: " + encodedAuthnResponse);
    }
    if (encodedAuthnResponse == null) {
        String[] data = { FSUtils.bundle.getString("missingAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.MISSING_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("missingAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    encodedAuthnResponse = encodedAuthnResponse.replace(' ', '\n');
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "Base64 encoded AuthnResponse2: " + encodedAuthnResponse);
    }
    FSAuthnResponse authnResponse = null;
    try {
        String decodedAuthnResponse = new String(Base64.decode(encodedAuthnResponse));
        FSUtils.debug.message("Decoded authnResponse" + decodedAuthnResponse);
        doc = XMLUtils.toDOMDocument(decodedAuthnResponse, FSUtils.debug);
        if (doc == null) {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSAssertionConsumerService.doPost:Error " + "while parsing input xml string");
            }
            throw new FSMsgException("parseError", null);
        }
        authnResponse = new FSAuthnResponse(doc.getDocumentElement());
        if (authnResponse == null) {
            FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. " + "Can't parse Base64 encoded AuthnResponse");
            String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
            LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
            FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
            FSUtils.forwardRequest(request, response, framedPageURL);
            return;
        }
    } catch (FSException e) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. FSException" + " occured while parsing Base64 encoded AuthnResponse: ", e);
        String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    } catch (SAMLException e) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. SAMLException" + " occurred while parsing Base64 encoded AuthnResponse: ", e);
        String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    try {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "AuthnResponse received is valid: " + authnResponse.toXMLString());
        }
    } catch (FSException e) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. FSException" + " occurred while calling AuthnResponse.toXMLString(): ", e);
        String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    FSAuthnRequest authnRequest = null;
    String requestID = authnResponse.getInResponseTo();
    if (requestID == null) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. AuthnResponse " + "received does not have inResponseTo attribute");
        String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "AuthnResponse received is against requestID: " + requestID);
    }
    authnRequest = getInResponseToRequest(requestID, metaAlias);
    if (authnRequest == null) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. AuthnResponse" + " received does not have an associated AuthnRequest");
        String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
        LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedPageURL);
        return;
    }
    String framedLoginPageURL = FSServiceUtils.getCommonLoginPageURL(metaAlias, authnRequest.getRelayState(), null, request, baseURL);
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "inResponseTo validation is successful");
    }
    try {
        String idpEntityId = null;
        IDPDescriptorType idpDescriptor = null;
        if (!authnRequest.getProtocolProfile().equals(IFSConstants.SSO_PROF_LECP)) {
            idpEntityId = getProvider(authnResponse.getInResponseTo(), metaAlias);
            idpDescriptor = metaManager.getIDPDescriptor(realm, idpEntityId);
            if (idpEntityId == null || idpDescriptor == null) {
                FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Invalid AuthnResponse. Sender information " + "not found for the received AuthnResponse");
                String[] data = { FSUtils.bundle.getString("invalidAuthnResponse") };
                LogUtil.error(Level.INFO, LogUtil.INVALID_AUTHN_RESPONSE, data);
                FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("invalidAuthnResponse") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
                FSUtils.forwardRequest(request, response, framedLoginPageURL);
                return;
            }
            if ((FSServiceUtils.isSigningOn() || (FSServiceUtils.isSigningOptional() && authnRequest.getProtocolProfile().equals(IFSConstants.SSO_PROF_BROWSER_POST))) && !verifyAuthnResponseSignature(doc, idpDescriptor, idpEntityId)) {
                FSUtils.debug.error("FSAssertionConsumerService.doPost: Signature " + "verification failed");
                FSUtils.forwardRequest(request, response, framedLoginPageURL);
                return;
            }
        } else {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSAssertionConsumerService.doPost: " + "LECP Profile identified. IDP info is unknown so far" + "Get providerId from the response");
            }
            idpEntityId = authnResponse.getProviderId();
            idpDescriptor = metaManager.getIDPDescriptor(realm, idpEntityId);
        }
        // handle sso
        FSServiceManager sm = FSServiceManager.getInstance();
        FSAssertionArtifactHandler handler = sm.getAssertionArtifactHandler(request, response, authnRequest, authnResponse, idpDescriptor, idpEntityId);
        if (handler == null) {
            FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "could not create AssertionArtifactHandler");
            String[] data = { FSUtils.bundle.getString("requestProcessingFailed") };
            LogUtil.error(Level.INFO, LogUtil.AUTHN_REQUEST_PROCESSING_FAILED, data);
            FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("requestProcessingFailed") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
            FSUtils.forwardRequest(request, response, framedLoginPageURL);
            return;
        }
        handler.setHostEntityId(hostEntityId);
        handler.setHostDescriptor(hostDesc);
        handler.setHostDescriptorConfig(hostConfig);
        handler.setMetaAlias(metaAlias);
        handler.setRealm(realm);
        handler.processAuthnResponse(authnResponse);
        return;
    } catch (Exception se) {
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + "Exception: ", se);
        FSUtils.debug.error("FSAssertionConsumerService.doPost: " + FSUtils.bundle.getString("requestProcessingFailed") + " AuthnRequest Processing Failed at the IDP" + " Redirecting to the Framed Login Page");
        FSUtils.forwardRequest(request, response, framedLoginPageURL);
        return;
    }
}
Also used : FSMsgException(com.sun.identity.federation.message.common.FSMsgException) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) Document(org.w3c.dom.Document) SPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.SPDescriptorType) SAMLException(com.sun.identity.saml.common.SAMLException) ServletException(javax.servlet.ServletException) SAMLException(com.sun.identity.saml.common.SAMLException) FSException(com.sun.identity.federation.common.FSException) IOException(java.io.IOException) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) FSServiceManager(com.sun.identity.federation.services.FSServiceManager) FSAuthnResponse(com.sun.identity.federation.message.FSAuthnResponse) FSException(com.sun.identity.federation.common.FSException)

Example 10 with FSAuthnRequest

use of com.sun.identity.federation.message.FSAuthnRequest in project OpenAM by OpenRock.

the class FSLoginHelper method createAuthnRequestEnvelope.

/**
     * Creates <code>AuthnRequestEnvelope</code> for <code>LECP</code> profile.
     * @param request <code>HttpServletRequest</code> object
     * @return xml string of an <code>AuthnRequestEnvelope</code> object
     */
public String createAuthnRequestEnvelope(HttpServletRequest request) {
    if (FSUtils.debug.messageEnabled()) {
        FSUtils.debug.message("FSLoginHelper.createAuthnRequestEnvelope(): called" + request.getParameter("metaAlias"));
    }
    try {
        String metaAlias = request.getParameter("metaAlias");
        //FSServiceUtils.getMetaAlias(request);
        setMetaInfo(metaAlias, null);
        FSAuthnRequest authnRequest = null;
        Map headerMap = new HashMap();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String hn = headerNames.nextElement().toString();
            String hv = request.getHeader(hn);
            headerMap.put(hn, hv);
        }
        Set idpSet = getIDPs(metaAlias);
        String LRURL = request.getParameter(IFSConstants.LRURL);
        if (LRURL == null || LRURL.equals("")) {
            LRURL = FSServiceUtils.getFederationDonePageURL(request, hostConfig, metaAlias);
        }
        authnRequest = getAuthnReq(headerMap, LRURL, true);
        authnRequest.setMinorVersion(FSServiceUtils.getMinorVersion(hostDescriptor.getProtocolSupportEnumeration()));
        if (authnRequest == null) {
            FSUtils.debug.error("FSLoginHelper.createAuthnRequest()::AuthnRequest is null");
            return errorPage + "&" + IFSConstants.FEDERROR + "=" + URLEncDec.encode("Unable to create AuthnRequest") + "&" + IFSConstants.FEDREMARK + "=" + URLEncDec.encode("Please check your Federation Configuration.");
        }
        String requestID = authnRequest.getRequestID();
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSLoginHelper.createAuthnRequest()::RequestID: " + requestID);
        }
        FSSessionManager sessMngr = FSSessionManager.getInstance(metaAlias);
        sessMngr.setAuthnRequest(requestID, authnRequest);
        Object ssoToken = SessionManager.getProvider().getSession(request);
        if (ssoToken != null) {
            sessMngr.setLocalSessionToken(requestID, ssoToken);
        }
        //check if dontgotothird level domain flag is off is yes
        //if yes then get one provider and and send to intersiteurl
        //else send to third level domain for provider id
        //also check if there is a single idp if yes go to intersite 
        //transfer with providerid
        //*****************
        FSAuthnRequestEnvelope authnRequestEnvelope = null;
        boolean isPassive = false;
        FSIDPList idpList = null;
        //get IDPList from directory
        String assertionConsumerURL = FSServiceUtils.getAssertionConsumerServiceURL(hostDescriptor, null);
        List idpEntryList = null;
        String idpID = null;
        String idpLocation = null;
        Iterator iter = idpSet.iterator();
        while (iter.hasNext()) {
            idpID = (String) iter.next();
            if (idpID != null) {
                IDPDescriptorType idpDescr = metaManager.getIDPDescriptor(realm, idpID);
                idpLocation = idpDescr.getSingleSignOnServiceURL();
                if (idpEntryList == null) {
                    idpEntryList = new ArrayList();
                }
                idpEntryList.add(new IDPEntry(idpID, idpID, idpLocation));
            }
        }
        int minorVersion = FSServiceUtils.getMinorVersion(hostDescriptor.getProtocolSupportEnumeration());
        IDPEntries idpEntries = new IDPEntries(idpEntryList);
        idpList = new FSIDPList(idpEntries, null);
        idpList.setMinorVersion(minorVersion);
        if (FSServiceUtils.isSigningOn()) {
            if (hostDescriptor.isAuthnRequestsSigned()) {
                authnRequest.signXML(IDFFMetaUtils.getFirstAttributeValueFromConfig(hostConfig, IFSConstants.SIGNING_CERT_ALIAS));
            }
        }
        authnRequestEnvelope = new FSAuthnRequestEnvelope(authnRequest, hostEntityID, hostEntityID, assertionConsumerURL, idpList, isPassive);
        authnRequestEnvelope.setMinorVersion(minorVersion);
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSLoginHelper.createAuthnRequest: " + "AuthnRequestEnvelope: " + authnRequestEnvelope.toXMLString());
        }
        return authnRequestEnvelope.toXMLString();
    } catch (Exception e) {
        FSUtils.debug.error("FSLoginHelper.createAuthnRequest():Exception Occured: ", e);
        return null;
    }
}
Also used : Enumeration(java.util.Enumeration) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) FSAuthnRequest(com.sun.identity.federation.message.FSAuthnRequest) FSAuthnRequestEnvelope(com.sun.identity.federation.message.FSAuthnRequestEnvelope) ArrayList(java.util.ArrayList) IDPEntries(com.sun.identity.federation.message.common.IDPEntries) COTException(com.sun.identity.cot.COTException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) FSIDPList(com.sun.identity.federation.message.FSIDPList) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) FSIDPList(com.sun.identity.federation.message.FSIDPList) IDPEntry(com.sun.identity.federation.message.common.IDPEntry) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

FSAuthnRequest (com.sun.identity.federation.message.FSAuthnRequest)15 IDPDescriptorType (com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType)11 FSException (com.sun.identity.federation.common.FSException)10 BaseConfigType (com.sun.identity.federation.jaxb.entityconfig.BaseConfigType)9 IDFFMetaException (com.sun.identity.federation.meta.IDFFMetaException)8 IOException (java.io.IOException)8 FSSessionManager (com.sun.identity.federation.services.FSSessionManager)7 FSAccountMgmtException (com.sun.identity.federation.accountmgmt.FSAccountMgmtException)6 SessionException (com.sun.identity.plugin.session.SessionException)6 Iterator (java.util.Iterator)6 List (java.util.List)6 ServletException (javax.servlet.ServletException)6 IDFFMetaManager (com.sun.identity.federation.meta.IDFFMetaManager)5 SPDescriptorType (com.sun.identity.liberty.ws.meta.jaxb.SPDescriptorType)5 SAMLException (com.sun.identity.saml.common.SAMLException)5 COTException (com.sun.identity.cot.COTException)4 FSIDPList (com.sun.identity.federation.message.FSIDPList)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4