Search in sources :

Example 6 with AuthnContext

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

the class IDPSSOUtil method getResponse.

/**
     * Returns a <code>SAML Response</code> object.
     *
     * @param request The HTTP request.
     * @param session The user's session object.
     * @param authnReq The <code>AuthnRequest</code> object.
     * @param recipientEntityID The entity ID of the response recipient.
     * @param idpEntityID The entity ID of the identity provider.
     * @param realm The realm name.
     * @param nameIDFormat The <code>NameIDFormat</code>.
     * @param acsURL The <code>ACS</code> service <code>url</code>.
     * @param affiliationID AffiliationID for IDP initiated SSO.
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
     * @return the <code>SAML Response</code> object.
     * @throws SAML2Exception if the operation is not successful.
     */
public static Response getResponse(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getResponse: ";
    Response res = ProtocolFactory.getInstance().createResponse();
    Status status = ProtocolFactory.getInstance().createStatus();
    if (status == null) {
        return null;
    }
    StatusCode statusCode = ProtocolFactory.getInstance().createStatusCode();
    if (statusCode == null) {
        return null;
    }
    try {
        List assertionList = new ArrayList();
        Assertion assertion = getAssertion(request, session, authnReq, recipientEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, acsURL, affiliationID, matchingAuthnContext);
        if (assertion == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get Assertion.");
            return null;
        }
        assertionList.add(assertion);
        res.setAssertion(assertionList);
        statusCode.setValue(SAML2Constants.SUCCESS);
    } catch (SAML2InvalidNameIDPolicyException se) {
        statusCode.setValue(SAML2Constants.REQUESTER);
        StatusCode subStatusCode = ProtocolFactory.getInstance().createStatusCode();
        subStatusCode.setValue(SAML2Constants.INVALID_NAME_ID_POLICY);
        statusCode.setStatusCode(subStatusCode);
        status.setStatusMessage(se.getMessage());
    }
    status.setStatusCode(statusCode);
    res.setStatus(status);
    if (authnReq != null) {
        // sp initiated case, need to set InResponseTo attribute
        res.setInResponseTo(authnReq.getID());
    }
    res.setVersion(SAML2Constants.VERSION_2_0);
    res.setIssueInstant(new Date());
    res.setID(SAML2Utils.generateID());
    // set the idp entity id as the response issuer
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    res.setIssuer(issuer);
    res.setDestination(XMLUtils.escapeSpecialCharacters(acsURL));
    return res;
}
Also used : ECPResponse(com.sun.identity.saml2.ecp.ECPResponse) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Status(com.sun.identity.saml2.protocol.Status) Issuer(com.sun.identity.saml2.assertion.Issuer) ArrayList(java.util.ArrayList) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) List(java.util.List) ArrayList(java.util.ArrayList) SAML2InvalidNameIDPolicyException(com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException) StatusCode(com.sun.identity.saml2.protocol.StatusCode) Date(java.util.Date)

Example 7 with AuthnContext

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

the class IDPSSOUtil method getAssertion.

/**
     * Returns a <code>SAML Assertion</code> object
     *
     * @throws SAML2Exception if the operation is not successful
     * @param request The HTTP request.
     * @param session The user's session object.
     * @param authnReq The <code>AuthnRequest</code> object.
     * @param recipientEntityID The entity ID of the response recipient.
     * @param idpEntityID The entity ID of the identity provider.
     * @param realm The realm name.
     * @param nameIDFormat The <code>NameIDFormat</code>.
     * @param acsURL The <code>ACS</code> service <code>url</code>.
     * @param affiliationID AffiliationID for IDP initiated SSO.
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
     * @return the <code>SAML Assertion</code> object.
     * @throws SAML2Exception if the operation is not successful.
     */
private static Assertion getAssertion(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getAssertion: ";
    Assertion assertion = AssertionFactory.getInstance().createAssertion();
    String assertionID = SAML2Utils.generateID();
    assertion.setID(assertionID);
    assertion.setVersion(SAML2Constants.VERSION_2_0);
    assertion.setIssueInstant(new Date());
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    assertion.setIssuer(issuer);
    List statementList = new ArrayList();
    NewBoolean isNewSessionIndex = new NewBoolean();
    AuthnStatement authnStatement = null;
    IDPSession idpSession = null;
    String sessionIndex = null;
    String sessionID = sessionProvider.getSessionID(session);
    synchronized (sessionID) {
        authnStatement = getAuthnStatement(request, session, isNewSessionIndex, authnReq, idpEntityID, realm, matchingAuthnContext);
        if (authnStatement == null) {
            return null;
        }
        sessionIndex = authnStatement.getSessionIndex();
        if (isNewSessionIndex.getValue()) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "This is a new IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionID);
            }
            idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
            if (idpSession == null) {
                idpSession = new IDPSession(session);
            }
            // Set the metaAlias in the IDP session object
            idpSession.setMetaAlias(idpMetaAlias);
            IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
            }
        } else {
            idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
        }
    }
    if (isNewSessionIndex.getValue()) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "a new IDP session has been saved in cache, " + "with sessionIndex=" + sessionIndex);
        }
        try {
            sessionProvider.addListener(session, sessionListener);
        } catch (SessionException e) {
            SAML2Utils.debug.error(classMethod + "Unable to add session listener.");
        }
    } else {
        if (idpSession == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            // Read from SAML2 Token Repository
            IDPSessionCopy idpSessionCopy = null;
            try {
                idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + "Unable to obtain IDPSessionCopy from the SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
            }
            // Copy back to IDPSession
            if (idpSessionCopy != null) {
                idpSession = new IDPSession(idpSessionCopy);
            } else {
                SAML2Utils.debug.error("IDPSessionCopy is null");
                throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
            }
        } else if ((idpSession == null) && (!SAML2FailoverUtils.isSAML2FailoverEnabled())) {
            SAML2Utils.debug.error("IDPSession is null; SAML2 failover" + "is disabled");
            throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
        } else {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "This is an existing IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionProvider.getSessionID(idpSession.getSession()));
            }
        }
    }
    statementList.add(authnStatement);
    AttributeStatement attrStatement = getAttributeStatement(session, idpEntityID, recipientEntityID, realm);
    if (attrStatement != null) {
        List attrStatementList = new ArrayList();
        attrStatementList.add(attrStatement);
        assertion.setAttributeStatements(attrStatementList);
    }
    // get the assertion effective time (in seconds)
    int effectiveTime = getEffectiveTime(realm, idpEntityID);
    // get the NotBefore skew (in seconds)
    int notBeforeSkewTime = getNotBeforeSkewTime(realm, idpEntityID);
    // get the subject element
    Subject subject = getSubject(session, authnReq, acsURL, nameIDFormat, realm, idpEntityID, recipientEntityID, effectiveTime, affiliationID);
    // register (spEntityID, nameID) with the sso token
    // for later logout use 
    String spEntityID = null;
    if (authnReq != null) {
        spEntityID = authnReq.getIssuer().getValue();
    } else {
        spEntityID = recipientEntityID;
    }
    NameIDandSPpair pair = new NameIDandSPpair(subject.getNameID(), spEntityID);
    synchronized (IDPCache.idpSessionsByIndices) {
        List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
        String id;
        if (authnReq != null) {
            id = authnReq.getIssuer().getValue();
        } else {
            id = spEntityID;
        }
        boolean found = false;
        for (NameIDandSPpair nameIDandSPpair : list) {
            if (nameIDandSPpair.getSPEntityID().equals(id)) {
                found = true;
                break;
            }
        }
        if (!found) {
            list.add(pair);
        }
    }
    assertion.setAuthnStatements(statementList);
    assertion.setSubject(subject);
    Conditions conditions = getConditions(recipientEntityID, notBeforeSkewTime, effectiveTime);
    assertion.setConditions(conditions);
    String discoBootstrapEnabled = getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.DISCO_BOOTSTRAPPING_ENABLED);
    if ((discoBootstrapEnabled != null) && discoBootstrapEnabled.equalsIgnoreCase("true")) {
        List attrStatementList = assertion.getAttributeStatements();
        if (attrStatementList == null) {
            attrStatementList = new ArrayList();
            assertion.setAttributeStatements(attrStatementList);
        }
        DiscoveryBootstrap bootstrap = new DiscoveryBootstrap(session, subject, authnStatement.getAuthnContext().getAuthnContextClassRef(), spEntityID, realm);
        attrStatementList.add(bootstrap.getBootstrapStatement());
        assertion.setAdvice(bootstrap.getCredentials());
    }
    if (assertionCacheEnabled(realm, idpEntityID)) {
        String userName = null;
        try {
            userName = sessionProvider.getPrincipalName(session);
        } catch (SessionException se) {
            SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
        }
        String cacheKey = userName.toLowerCase();
        List assertions = (List) IDPCache.assertionCache.get(cacheKey);
        if (assertions == null) {
            synchronized (IDPCache.assertionCache) {
                assertions = (List) IDPCache.assertionCache.get(cacheKey);
                if (assertions == null) {
                    assertions = new ArrayList();
                    IDPCache.assertionCache.put(cacheKey, assertions);
                }
            }
        }
        synchronized (assertions) {
            assertions.add(assertion);
        }
        IDPCache.assertionByIDCache.put(assertionID, assertion);
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            try {
                SAML2FailoverUtils.saveSAML2Token(assertionID, cacheKey, assertion.toXMLString(true, true), conditions.getNotOnOrAfter().getTime() / 1000);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Saving Assertion to SAML2 Token Repository. ID = " + assertionID);
                }
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + "Unable to save Assertion to the SAML2 Token Repository", se);
            }
        }
    }
    //  Save to SAML2 Token Repository
    try {
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            long sessionExpireTime = System.currentTimeMillis() / 1000 + (sessionProvider.getTimeLeft(session));
            SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), sessionExpireTime);
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "SAVE IDPSession!");
        }
    } catch (SessionException se) {
        SAML2Utils.debug.error(classMethod + "Unable to get left-time from the session.", se);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    } catch (SAML2TokenRepositoryException se) {
        SAML2Utils.debug.error(classMethod + "Unable to save IDPSession to the SAML2 Token Repository", se);
    }
    return assertion;
}
Also used : Issuer(com.sun.identity.saml2.assertion.Issuer) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) NewBoolean(com.sun.identity.saml2.common.NewBoolean) SessionException(com.sun.identity.plugin.session.SessionException) Date(java.util.Date) Subject(com.sun.identity.saml2.assertion.Subject) Conditions(com.sun.identity.saml2.assertion.Conditions) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) List(java.util.List) ArrayList(java.util.ArrayList) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)

Example 8 with AuthnContext

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

the class IDPSSOUtil method sendResponseToACS.

/**
     * Sends <code>Response</code> containing an <code>Assertion</code>
     * back to the requesting service provider
     *
     * @param request              the <code>HttpServletRequest</code> object
     * @param response             the <code>HttpServletResponse</code> object
     * @param out                  the print writer for writing out presentation
     * @param session              user session
     * @param authnReq             the <code>AuthnRequest</code> object
     * @param spEntityID           the entity id of the service provider
     * @param idpEntityID          the entity id of the identity provider
     * @param idpMetaAlias         the meta alias of the identity provider
     * @param realm                the realm
     * @param nameIDFormat         the <code>NameIDFormat</code>
     * @param relayState           the relay state
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find
     *                             authentication type and scheme.
     */
public static void sendResponseToACS(HttpServletRequest request, HttpServletResponse response, PrintWriter out, Object session, AuthnRequest authnReq, String spEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String relayState, AuthnContext matchingAuthnContext) throws SAML2Exception {
    StringBuffer returnedBinding = new StringBuffer();
    String acsURL = IDPSSOUtil.getACSurl(spEntityID, realm, authnReq, request, returnedBinding);
    String acsBinding = returnedBinding.toString();
    if ((acsURL == null) || (acsURL.trim().length() == 0)) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no ACS URL found.");
        String[] data = { idpMetaAlias };
        LogUtil.error(Level.INFO, LogUtil.NO_ACS_URL, data, session);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindACSURL"));
    }
    if ((acsBinding == null) || (acsBinding.trim().length() == 0)) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no return binding found.");
        String[] data = { idpMetaAlias };
        LogUtil.error(Level.INFO, LogUtil.NO_RETURN_BINDING, data, session);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
    }
    String affiliationID = request.getParameter(SAML2Constants.AFFILIATION_ID);
    //check first if there is already an existing sessionindex associated with this SSOToken, if there is, then
    //we need to redirect the request internally to the holder of the idpsession.
    //The remoteServiceURL will be null if there is no sessionindex for this SSOToken, or there is, but it's
    //local. If the remoteServiceURL is not null, we can start to send the request to the original server.
    String remoteServiceURL = SAML2Utils.getRemoteServiceURL(getSessionIndex(session));
    if (remoteServiceURL != null) {
        remoteServiceURL += SAML2Utils.removeDeployUri(request.getRequestURI()) + "?" + request.getQueryString();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SessionIndex for this SSOToken is not local, forwarding the request to: " + remoteServiceURL);
        }
        String redirectUrl = null;
        String outputData = null;
        String responseCode = null;
        HashMap<String, String> remoteRequestData = SAML2Utils.sendRequestToOrigServer(request, response, remoteServiceURL);
        if (remoteRequestData != null && !remoteRequestData.isEmpty()) {
            redirectUrl = remoteRequestData.get(SAML2Constants.AM_REDIRECT_URL);
            outputData = remoteRequestData.get(SAML2Constants.OUTPUT_DATA);
            responseCode = remoteRequestData.get(SAML2Constants.RESPONSE_CODE);
        }
        try {
            if (redirectUrl != null && !redirectUrl.isEmpty()) {
                response.sendRedirect(redirectUrl);
            } else {
                if (responseCode != null) {
                    response.setStatus(Integer.valueOf(responseCode));
                }
                // no redirect, perhaps an error page, return the content
                if (outputData != null && !outputData.isEmpty()) {
                    SAML2Utils.debug.message("Printing the forwarded response");
                    response.setContentType("text/html; charset=UTF-8");
                    out.println(outputData);
                    return;
                }
            }
        } catch (IOException ioe) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS() error in Request Routing", ioe);
            }
        }
        return;
    }
    //end of request proxy
    // generate a response for the authn request
    Response res = getResponse(request, session, authnReq, spEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, acsURL, affiliationID, matchingAuthnContext);
    if (res == null) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " response is null");
        String errorMsg = SAML2Utils.bundle.getString("UnableToCreateAssertion");
        if (authnReq == null) {
            //idp initiated case, will not send error response to sp
            throw new SAML2Exception(errorMsg);
        }
        res = SAML2Utils.getErrorResponse(authnReq, SAML2Constants.RESPONDER, null, errorMsg, idpEntityID);
    } else {
        try {
            String[] values = { idpMetaAlias };
            sessionProvider.setProperty(session, SAML2Constants.IDP_META_ALIAS, values);
        } catch (SessionException e) {
            SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error setting idpMetaAlias into the session: ", e);
        }
    }
    if (res != null) {
        // call multi-federation protocol to set the protocol
        MultiProtocolUtils.addFederationProtocol(session, SingleLogoutManager.SAML2);
        // check if the COT cookie needs to be set
        if (setCOTCookie(request, response, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session)) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Redirected to set COT cookie.");
            }
            return;
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Doesn't set COT cookie.");
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Response is:  " + res.toXMLString());
        }
        try {
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS: Invoking the IDP Adapter");
            SAML2IdentityProviderAdapter idpAdapter = IDPSSOUtil.getIDPAdapterClass(realm, idpEntityID);
            if (idpAdapter != null) {
                idpAdapter.preSignResponse(authnReq, res, idpEntityID, realm, request, session, relayState);
            }
        } catch (SAML2Exception se) {
            SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS: There was a problem when invoking the " + "preSendResponse of the IDP Adapter: ", se);
        }
        sendResponse(request, response, out, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session);
    } else {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error response is null");
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToCreateErrorResponse"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ECPResponse(com.sun.identity.saml2.ecp.ECPResponse) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) SAML2IdentityProviderAdapter(com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter)

Example 9 with AuthnContext

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

the class AuthnContextImpl method parseElement.

// used by the constructors.
private void parseElement(org.w3c.dom.Element element) throws com.sun.identity.saml2.common.SAML2Exception {
    // make sure that the input xml block is not null
    if (element == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("AuthnContextImpl.parseElement:" + " Input is null.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    // Make sure this is an AuthnContext.
    String tag = null;
    tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("AuthnContext"))) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("AuthnContextImpl.parseElement:" + " not AuthnContext.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
    }
    NodeList nl = element.getChildNodes();
    Node child;
    String childName;
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        child = nl.item(i);
        if ((childName = child.getLocalName()) != null) {
            if (childName.equals("AuthnContextClassRef")) {
                if (authnContextClassRef != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl.parse" + "Element: included more than one AuthnContext" + "ClassRef.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (authnContextDecl != null || authnContextDeclRef != null || authenticatingAuthority != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl.parse" + "Element: AuthnContextClassRef should be " + "the first child element.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                authnContextClassRef = XMLUtils.getElementValue((Element) child);
                if (authnContextClassRef == null || authnContextClassRef.trim().length() == 0) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl." + "parseElement: value for AuthnContextClassRef " + "is empty.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementValue"));
                }
            } else if (childName.equals("AuthnContextDecl")) {
                if (authnContextDecl != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl.parse" + "Element: included more than one AuthnContext" + "Decl.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                authnContextDecl = XMLUtils.print(child);
                if (authnContextDecl == null || authnContextDecl.trim().length() == 0) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl." + "parseElement: value for AuthnContextDecl " + "is empty.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementValue"));
                }
            } else if (childName.equals("AuthnContextDeclRef")) {
                if (authnContextDeclRef != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl.parse" + "Element: included more than one AuthnContext" + "DeclRef.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                authnContextDeclRef = XMLUtils.getElementValue((Element) child);
                if (authnContextDeclRef == null || authnContextDeclRef.trim().length() == 0) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl." + "parseElement: value for AuthnContextDeclRef " + "is empty.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementValue"));
                }
            } else if (childName.equals("AuthenticatingAuthority")) {
                String authority = XMLUtils.getElementValue((Element) child);
                if (authority == null || authority.trim().length() == 0) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnContextImpl." + "parseElement: value for" + " AuthenticatingAuthority is empty.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missingElementValue"));
                }
                if (authenticatingAuthority == null) {
                    authenticatingAuthority = new ArrayList<String>();
                }
                authenticatingAuthority.add(authority);
            } else {
                if (SAML2SDKUtils.debug.messageEnabled()) {
                    SAML2SDKUtils.debug.message("AuthnContextImpl." + "parseElement: Invalid element:" + childName);
                }
                throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
            }
        }
    }
    // validateData();
    if (authenticatingAuthority != null) {
        authenticatingAuthority = Collections.unmodifiableList(authenticatingAuthority);
    }
    mutable = false;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList)

Example 10 with AuthnContext

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

the class AuthnStatementImpl method parseElement.

// used by the constructors.
private void parseElement(Element element) throws SAML2Exception {
    // make sure that the input xml block is not null
    if (element == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("AuthnStatementImpl.parseElement: " + "Input is null.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    // Make sure this is an AuthnStatement.
    if (!SAML2SDKUtils.checkStatement(element, "AuthnStatement")) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("AuthnStatementImpl.parseElement: " + "not AuthnStatement.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("wrongInput"));
    }
    // handle the attributes of <AuthnStatement> element
    NamedNodeMap atts = ((Node) element).getAttributes();
    if (atts != null) {
        Node att = atts.getNamedItem("AuthnInstant");
        if (att != null) {
            try {
                authnInstant = DateUtils.stringToDate(((Attr) att).getValue().trim());
            } catch (ParseException pe) {
                throw new SAML2Exception(pe.getMessage());
            }
        }
        att = atts.getNamedItem("SessionIndex");
        if (att != null) {
            sessionIndex = ((Attr) att).getValue().trim();
        }
        att = atts.getNamedItem("SessionNotOnOrAfter");
        if (att != null) {
            try {
                sessionNotOnOrAfter = DateUtils.stringToDate(((Attr) att).getValue().trim());
            } catch (ParseException pe) {
                throw new SAML2Exception(pe.getMessage());
            }
        }
    }
    // handle the sub elementsof the AuthnStatment
    NodeList nl = element.getChildNodes();
    Node child;
    String childName;
    int length = nl.getLength();
    for (int i = 0; i < length; i++) {
        child = nl.item(i);
        if ((childName = child.getLocalName()) != null) {
            if (childName.equals("SubjectLocality")) {
                if (subjectLocality != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: included more than one Subject" + "Locality.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                if (authnContext != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: SubjectLocality is out of " + "sequence.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("schemaViolation"));
                }
                subjectLocality = AssertionFactory.getInstance().createSubjectLocality((Element) child);
            } else if (childName.equals("AuthnContext")) {
                if (authnContext != null) {
                    if (SAML2SDKUtils.debug.messageEnabled()) {
                        SAML2SDKUtils.debug.message("AuthnStatementImpl." + "parseElement: included more than one " + "AuthnContext.");
                    }
                    throw new SAML2Exception(SAML2SDKUtils.bundle.getString("moreElement"));
                }
                authnContext = AssertionFactory.getInstance().createAuthnContext((Element) child);
            } else {
                if (SAML2SDKUtils.debug.messageEnabled()) {
                    SAML2SDKUtils.debug.message("AuthnStatementImpl.parse" + "Element: Invalid element:" + childName);
                }
                throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElement"));
            }
        }
    }
    validateData();
    mutable = false;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NamedNodeMap(org.w3c.dom.NamedNodeMap) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ParseException(java.text.ParseException) Attr(org.w3c.dom.Attr)

Aggregations

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