Search in sources :

Example 6 with ResponseInfo

use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.

the class SPACSUtils method processResponse.

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

Example 7 with ResponseInfo

use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.

the class SAML2PostAuthenticationPlugin method configurePostSSO.

private void configurePostSSO(String spEntityId, String realm, HttpServletRequest request, HttpServletResponse response, SSOToken session, SessionProvider sessionProvider, ResponseInfo respInfo, String cacheKey) throws SAML2Exception {
    AuthnRequest authnReq = (AuthnRequest) SPCache.authnRequestHash.get(cacheKey);
    boolean writeFedInfo = Boolean.parseBoolean((String) SPCache.fedAccountHash.get(cacheKey));
    final SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityId, realm);
    if (spAdapter != null) {
        final boolean redirected = spAdapter.postSingleSignOnSuccess(spEntityId, realm, request, response, null, session, authnReq, respInfo.getResponse(), respInfo.getProfileBinding(), writeFedInfo);
        final String[] value = new String[] { String.valueOf(redirected) };
        try {
            sessionProvider.setProperty(session, SAML2Constants.RESPONSE_REDIRECTED, value);
        } catch (SessionException | UnsupportedOperationException ex) {
            DEBUG.warning("SAML2PostAuthenticationPlugin.configurePostSSO :: failed to set properties in session.", ex);
        }
    }
    SPCache.authnRequestHash.remove(cacheKey);
    SPCache.fedAccountHash.remove(cacheKey);
}
Also used : AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SessionException(com.sun.identity.plugin.session.SessionException) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter)

Example 8 with ResponseInfo

use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.

the class IDPProxyUtil method generateProxyResponse.

/**
     * Generates the AuthnResponse by the IDP Proxy and send to the service provider.
     *
     * @param request HttpServletRequest The HTTP request.
     * @param response HttpServletResponse The HTTP response.
     * @param out The print writer for writing out presentation.
     * @param metaAlias The meta alias.
     * @param respInfo ResponseInfo object.
     * @param newSession Session object.
     * @throws SAML2Exception for any SAML2 failure.
     */
public static void generateProxyResponse(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String metaAlias, ResponseInfo respInfo, Object newSession) throws SAML2Exception {
    Response saml2Resp = respInfo.getResponse();
    String requestID = saml2Resp.getInResponseTo();
    String nameidFormat = getNameIDFormat(saml2Resp);
    if (nameidFormat != null && SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("NAME ID Format= " + nameidFormat);
    }
    // Save the SAML response received from the IdP in the request object, so that we can access the original
    // assertion when generating the new one.
    request.setAttribute(SAML2Constants.SAML_PROXY_IDP_RESPONSE_KEY, saml2Resp);
    sendProxyResponse(request, response, out, requestID, metaAlias, newSession, nameidFormat);
}
Also used : Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse)

Example 9 with ResponseInfo

use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.

the class SPACSUtils method getResponseFromPost.

// Obtains SAML Response from POST.
private static ResponseInfo getResponseFromPost(HttpServletRequest request, HttpServletResponse response, String orgName, String hostEntityId, SAML2MetaManager metaManager) throws SAML2Exception, IOException {
    String classMethod = "SPACSUtils:getResponseFromPost";
    SAML2Utils.debug.message("SPACSUtils:getResponseFromPost");
    String samlArt = request.getParameter(SAML2Constants.SAML_ART);
    if ((samlArt != null) && (samlArt.trim().length() != 0)) {
        return new ResponseInfo(getResponseFromArtifact(samlArt, hostEntityId, request, response, orgName, metaManager), SAML2Constants.HTTP_ARTIFACT, null);
    }
    String samlResponse = request.getParameter(SAML2Constants.SAML_RESPONSE);
    if (samlResponse == null) {
        LogUtil.error(Level.INFO, LogUtil.MISSING_SAML_RESPONSE_FROM_POST, null, null);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "missingSAMLResponse", SAML2Utils.bundle.getString("missingSAMLResponse"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSAMLResponse"));
    }
    // Get Response back
    // decode the Response
    Response resp = null;
    ByteArrayInputStream bis = null;
    try {
        byte[] raw = Base64.decode(samlResponse);
        if (raw != null) {
            bis = new ByteArrayInputStream(raw);
            Document doc = XMLUtils.toDOMDocument(bis, SAML2Utils.debug);
            if (doc != null) {
                resp = ProtocolFactory.getInstance().createResponse(doc.getDocumentElement());
            }
        }
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("SPACSUtils.getResponse: Exception " + "when instantiating SAMLResponse:", se);
        LogUtil.error(Level.INFO, LogUtil.CANNOT_INSTANTIATE_RESPONSE_POST, null, null);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "errorObtainResponse", SAML2Utils.bundle.getString("errorObtainResponse"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorObtainResponse"));
    } catch (Exception e) {
        SAML2Utils.debug.error("SPACSUtils.getResponse: Exception " + "when decoding SAMLResponse:", e);
        LogUtil.error(Level.INFO, LogUtil.CANNOT_DECODE_RESPONSE, null, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorDecodeResponse", SAML2Utils.bundle.getString("errorDecodeResponse"));
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorDecodeResponse"));
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception ie) {
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("SPACSUtils.getResponse: " + "Exception when close the input stream:", ie);
                }
            }
        }
    }
    if (resp != null) {
        String[] data = { "" };
        if (LogUtil.isAccessLoggable(Level.FINE)) {
            data[0] = resp.toXMLString();
        }
        LogUtil.access(Level.INFO, LogUtil.GOT_RESPONSE_FROM_POST, data, null);
        return (new ResponseInfo(resp, SAML2Constants.HTTP_POST, null));
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPACSUtils.getResponse: Decoded response, " + "resp is null");
    }
    return null;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) Document(org.w3c.dom.Document) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) SOAPBindingException(com.sun.identity.liberty.ws.soapbinding.SOAPBindingException) SOAPFaultException(com.sun.identity.liberty.ws.soapbinding.SOAPFaultException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 10 with ResponseInfo

use of com.sun.identity.saml2.profile.ResponseInfo in project OpenAM by OpenRock.

the class SPACSUtils method invokeSPAdapterForSSOFailure.

private static void invokeSPAdapterForSSOFailure(String hostEntityId, String realm, HttpServletRequest request, HttpServletResponse response, Map smap, ResponseInfo respInfo, int errorCode, SAML2Exception se) {
    SAML2ServiceProviderAdapter spAdapter = null;
    try {
        spAdapter = SAML2Utils.getSPAdapterClass(hostEntityId, realm);
    } catch (SAML2Exception e) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPACSUtils.invokeSPAdapterForSSOFailure", e);
        }
    }
    if (spAdapter != null) {
        AuthnRequest authnRequest = null;
        if (smap != null) {
            authnRequest = (AuthnRequest) smap.get(SAML2Constants.AUTHN_REQUEST);
        }
        boolean redirected = spAdapter.postSingleSignOnFailure(hostEntityId, realm, request, response, authnRequest, respInfo.getResponse(), respInfo.getProfileBinding(), errorCode);
        se.setRedirectionDone(redirected);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)7 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)5 SessionException (com.sun.identity.plugin.session.SessionException)4 Response (com.sun.identity.saml2.protocol.Response)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 Assertion (com.sun.identity.saml2.assertion.Assertion)3 SAML2ServiceProviderAdapter (com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter)3 ArtifactResponse (com.sun.identity.saml2.protocol.ArtifactResponse)3 AuthnRequest (com.sun.identity.saml2.protocol.AuthnRequest)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Map (java.util.Map)3 ServletException (javax.servlet.ServletException)3 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)3 SOAPBindingException (com.sun.identity.liberty.ws.soapbinding.SOAPBindingException)2 SOAPFaultException (com.sun.identity.liberty.ws.soapbinding.SOAPFaultException)2 DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)2 SessionProvider (com.sun.identity.plugin.session.SessionProvider)2 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)2 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)2