Search in sources :

Example 1 with RequestedAuthnContext

use of org.opensaml.saml.saml2.core.RequestedAuthnContext in project cas by apereo.

the class DefaultAuthnContextClassRefBuilder method build.

@Override
public String build(final Assertion assertion, final AuthnRequest authnRequest, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final SamlRegisteredService service) {
    final RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    if (requestedAuthnContext == null) {
        LOGGER.debug("No specific authN context is requested. Returning [{}]", AuthnContext.UNSPECIFIED_AUTHN_CTX);
        return AuthnContext.UNSPECIFIED_AUTHN_CTX;
    }
    final List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
    if (authnContextClassRefs == null || authnContextClassRefs.isEmpty()) {
        LOGGER.debug("Requested authN context class ref is unspecified. Returning [{}]", AuthnContext.UNSPECIFIED_AUTHN_CTX);
        return AuthnContext.UNSPECIFIED_AUTHN_CTX;
    }
    LOGGER.debug("AuthN Context comparison is requested to use [{}]", requestedAuthnContext.getComparison());
    authnContextClassRefs.forEach(authnContextClassRef -> LOGGER.debug("Requested AuthN Context [{}]", authnContextClassRef.getAuthnContextClassRef()));
    if (StringUtils.isNotBlank(service.getRequiredAuthenticationContextClass())) {
        LOGGER.debug("Using [{}] as indicated by SAML registered service [{}]", service.getRequiredAuthenticationContextClass(), service.getName());
        return service.getRequiredAuthenticationContextClass();
    }
    LOGGER.debug("Returning default AuthN Context [{}]", AuthnContext.PPT_AUTHN_CTX);
    return AuthnContext.PPT_AUTHN_CTX;
}
Also used : RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef)

Example 2 with RequestedAuthnContext

use of org.opensaml.saml.saml2.core.RequestedAuthnContext in project ddf by codice.

the class IdpEndpoint method determineAuthMethod.

private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
    } catch (XMLStreamException e) {
        LOGGER.debug("Unable to parse SOAP message from client.", e);
    }
    SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
    SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
    soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
    preInInterceptor.handleMessage(soapMessage);
    SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
    inInterceptor.handleMessage(soapMessage);
    SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
    AuthObj authObj = new AuthObj();
    try {
        Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
        while (soapHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
            if (soapHeaderElement.getLocalName().equals("Security")) {
                Iterator childElements = soapHeaderElement.getChildElements();
                while (childElements.hasNext()) {
                    Object nextElement = childElements.next();
                    if (nextElement instanceof SOAPElement) {
                        SOAPElement element = (SOAPElement) nextElement;
                        if (element.getLocalName().equals("UsernameToken")) {
                            Iterator usernameTokenElements = element.getChildElements();
                            Object next;
                            while (usernameTokenElements.hasNext()) {
                                if ((next = usernameTokenElements.next()) instanceof Element) {
                                    Element nextEl = (Element) next;
                                    if (nextEl.getLocalName().equals("Username")) {
                                        authObj.username = nextEl.getTextContent();
                                    } else if (nextEl.getLocalName().equals("Password")) {
                                        authObj.password = nextEl.getTextContent();
                                    }
                                }
                            }
                            if (authObj.username != null && authObj.password != null) {
                                authObj.method = USER_PASS;
                                break;
                            }
                        } else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                            authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
                            authObj.method = SAML;
                            break;
                        }
                    }
                }
            }
        }
    } catch (SOAPException e) {
        LOGGER.debug("Unable to parse SOAP message.", e);
    }
    RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    boolean requestingPki = false;
    boolean requestingUp = false;
    if (requestedAuthnContext != null) {
        List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
        for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
            String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
            if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
                requestingPki = true;
            } else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
                requestingUp = true;
            }
        }
    } else {
        //The requested auth context isn't required so we don't know what they want... just set both to true
        requestingPki = true;
        requestingUp = true;
    }
    if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
        LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
        return authObj;
    } else if (requestingPki && authObj.method == null) {
        LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
        authObj.method = PKI;
        return authObj;
    } else if (authObj.method == null) {
        LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
    }
    return authObj;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) XMLStreamReader(javax.xml.stream.XMLStreamReader) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SAAJInInterceptor(org.apache.cxf.binding.soap.saaj.SAAJInInterceptor) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) StringReader(java.io.StringReader) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPElement(javax.xml.soap.SOAPElement) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 3 with RequestedAuthnContext

use of org.opensaml.saml.saml2.core.RequestedAuthnContext in project syncope by apache.

the class SAML2SPLogic method createLoginRequest.

@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2RequestTO createLoginRequest(final String spEntityID, final String idpEntityID) {
    check();
    // 1. look for IdP
    SAML2IdPEntity idp = StringUtils.isBlank(idpEntityID) ? cache.getFirst() : cache.get(idpEntityID);
    if (idp == null) {
        if (StringUtils.isBlank(idpEntityID)) {
            List<SAML2IdP> all = saml2IdPDAO.findAll();
            if (!all.isEmpty()) {
                idp = getIdP(all.get(0).getKey());
            }
        } else {
            idp = getIdP(idpEntityID);
        }
    }
    if (idp == null) {
        throw new NotFoundException(StringUtils.isBlank(idpEntityID) ? "Any SAML 2.0 IdP" : "SAML 2.0 IdP '" + idpEntityID + "'");
    }
    if (idp.getSSOLocation(idp.getBindingType()) == null) {
        throw new IllegalArgumentException("No SingleSignOnService available for " + idp.getId());
    }
    // 2. create AuthnRequest
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spEntityID);
    NameIDPolicy nameIDPolicy = new NameIDPolicyBuilder().buildObject();
    if (idp.supportsNameIDFormat(NameIDType.TRANSIENT)) {
        nameIDPolicy.setFormat(NameIDType.TRANSIENT);
    } else if (idp.supportsNameIDFormat(NameIDType.PERSISTENT)) {
        nameIDPolicy.setFormat(NameIDType.PERSISTENT);
    } else {
        throw new IllegalArgumentException("Could not find supported NameIDFormat for IdP " + idpEntityID);
    }
    nameIDPolicy.setAllowCreate(true);
    nameIDPolicy.setSPNameQualifier(spEntityID);
    AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    RequestedAuthnContext requestedAuthnContext = new RequestedAuthnContextBuilder().buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID("_" + UUID_GENERATOR.generate().toString());
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setProtocolBinding(idp.getBindingType().getUri());
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);
    authnRequest.setDestination(idp.getSSOLocation(idp.getBindingType()).getLocation());
    SAML2RequestTO requestTO = new SAML2RequestTO();
    requestTO.setIdpServiceAddress(authnRequest.getDestination());
    requestTO.setBindingType(idp.getBindingType());
    try {
        // 3. generate relay state as JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_CLAIM_IDP_DEFLATE, idp.isUseDeflateEncoding());
        Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(authnRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
        // 4. sign and encode AuthnRequest
        switch(idp.getBindingType()) {
            case REDIRECT:
                requestTO.setRelayState(URLEncoder.encode(relayState.getMiddle(), StandardCharsets.UTF_8.name()));
                requestTO.setContent(URLEncoder.encode(saml2rw.encode(authnRequest, true), StandardCharsets.UTF_8.name()));
                requestTO.setSignAlg(URLEncoder.encode(saml2rw.getSigAlgo(), StandardCharsets.UTF_8.name()));
                requestTO.setSignature(URLEncoder.encode(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()), StandardCharsets.UTF_8.name()));
                break;
            case POST:
            default:
                requestTO.setRelayState(relayState.getMiddle());
                saml2rw.sign(authnRequest);
                requestTO.setContent(saml2rw.encode(authnRequest, idp.isUseDeflateEncoding()));
        }
    } catch (Exception e) {
        LOG.error("While generating AuthnRequest", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return requestTO;
}
Also used : SAML2RequestTO(org.apache.syncope.common.lib.to.SAML2RequestTO) Issuer(org.opensaml.saml.saml2.core.Issuer) HashMap(java.util.HashMap) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) XSString(org.opensaml.core.xml.schema.XSString) AuthnContextClassRefBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder) DateTime(org.joda.time.DateTime) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) NameIDPolicyBuilder(org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Date(java.util.Date) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) RequestedAuthnContextBuilder(org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAML2IdPEntity(org.apache.syncope.core.logic.saml2.SAML2IdPEntity) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) XMLObject(org.opensaml.core.xml.XMLObject) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 4 with RequestedAuthnContext

use of org.opensaml.saml.saml2.core.RequestedAuthnContext in project cloudstack by apache.

the class SAMLUtils method buildAuthnRequestObject.

public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
    // Issuer object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spId);
    // AuthnContextClass
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(SAMLConstants.SAML20_NS, "AuthnContextClassRef", "saml");
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    // AuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    // Creation of AuthRequestObject
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authnRequest = authRequestBuilder.buildObject();
    authnRequest.setID(authnId);
    authnRequest.setDestination(idpUrl);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    authnRequest.setAssertionConsumerServiceURL(consumerUrl);
    authnRequest.setProviderName(spId);
    authnRequest.setIssuer(issuer);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);
    return authnRequest;
}
Also used : RequestedAuthnContextBuilder(org.opensaml.saml2.core.impl.RequestedAuthnContextBuilder) RequestedAuthnContext(org.opensaml.saml2.core.RequestedAuthnContext) AuthnRequest(org.opensaml.saml2.core.AuthnRequest) Issuer(org.opensaml.saml2.core.Issuer) AuthnContextClassRef(org.opensaml.saml2.core.AuthnContextClassRef) IssuerBuilder(org.opensaml.saml2.core.impl.IssuerBuilder) AuthnRequestBuilder(org.opensaml.saml2.core.impl.AuthnRequestBuilder) AuthnContextClassRefBuilder(org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder) DateTime(org.joda.time.DateTime)

Example 5 with RequestedAuthnContext

use of org.opensaml.saml.saml2.core.RequestedAuthnContext in project cas by apereo.

the class SamlIdPDelegatedAuthenticationConfigurationTests method verifyOperation.

@Test
public void verifyOperation() throws Exception {
    val service = getSamlRegisteredServiceFor("https://cassp.example.org");
    service.setId(2000);
    val authnRequest = SamlIdPTestUtils.getAuthnRequest(openSamlConfigBean, service);
    authnRequest.setForceAuthn(true);
    authnRequest.setIsPassive(true);
    var builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    val classRef = (AuthnContextClassRef) builder.buildObject(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    classRef.setURI("https://refeds.org/profile/mfa");
    builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
    val reqCtx = (RequestedAuthnContext) builder.buildObject(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
    reqCtx.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    reqCtx.getAuthnContextClassRefs().add(classRef);
    authnRequest.setRequestedAuthnContext(reqCtx);
    val request = new MockHttpServletRequest();
    val response = new MockHttpServletResponse();
    val webContext = new JEEContext(request, response);
    val messageContext = new MessageContext();
    messageContext.setMessage(authnRequest);
    val context = Pair.of(authnRequest, messageContext);
    SamlIdPUtils.storeSamlRequest(webContext, openSamlConfigBean, samlIdPDistributedSessionStore, context);
    val saml2Client = mock(SAML2Client.class);
    assertTrue(customizer.supports(saml2Client, webContext));
    customizer.customize(saml2Client, webContext);
    assertTrue(webContext.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN).isPresent());
    assertTrue(webContext.getRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE).isPresent());
    assertTrue(webContext.getRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_AUTHN_CONTEXT_CLASS_REFS).isPresent());
    assertTrue(webContext.getRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_COMPARISON_TYPE).isPresent());
}
Also used : lombok.val(lombok.val) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) JEEContext(org.pac4j.core.context.JEEContext) MessageContext(org.opensaml.messaging.context.MessageContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

RequestedAuthnContext (org.opensaml.saml.saml2.core.RequestedAuthnContext)16 AuthnContextClassRef (org.opensaml.saml.saml2.core.AuthnContextClassRef)13 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)13 lombok.val (lombok.val)5 Test (org.junit.jupiter.api.Test)5 NameIDPolicy (org.opensaml.saml.saml2.core.NameIDPolicy)5 DateTime (org.joda.time.DateTime)4 Issuer (org.opensaml.saml.saml2.core.Issuer)4 IdaAuthnRequestFromHub (uk.gov.ida.saml.hub.domain.IdaAuthnRequestFromHub)4 SAMLObjectBuilder (org.opensaml.saml.common.SAMLObjectBuilder)3 AuthnContextClassRefBuilder (org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder)3 IdaAuthnRequestBuilder.anIdaAuthnRequest (uk.gov.ida.saml.hub.test.builders.IdaAuthnRequestBuilder.anIdaAuthnRequest)3 XMLObject (org.opensaml.core.xml.XMLObject)2 MessageContext (org.opensaml.messaging.context.MessageContext)2 RequestedAuthnContextBuilder (org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder)2 JEEContext (org.pac4j.core.context.JEEContext)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)2 Inject (com.google.inject.Inject)1 StringReader (java.io.StringReader)1