Search in sources :

Example 11 with AuthnRequest

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

the class IdPInitiatedProfileHandlerController method handleIdPInitiatedSsoRequest.

/**
     * Handle idp initiated sso requests.
     *
     * @param response the response
     * @param request  the request
     * @throws Exception the exception
     */
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_IDP_INIT_PROFILE_SSO)
protected void handleIdPInitiatedSsoRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    // The name (i.e., the entity ID) of the service provider.
    final String providerId = CommonUtils.safeGetParameter(request, SamlIdPConstants.PROVIDER_ID);
    if (StringUtils.isBlank(providerId)) {
        LOGGER.warn("No providerId parameter given in unsolicited SSO authentication request.");
        throw new MessageDecodingException("No providerId parameter given in unsolicited SSO authentication request.");
    }
    final SamlRegisteredService registeredService = verifySamlRegisteredService(providerId);
    final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(registeredService, providerId);
    if (!adaptor.isPresent()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + providerId);
    }
    // The URL of the response location at the SP (called the "Assertion Consumer Service")
    // but can be omitted in favor of the IdP picking the default endpoint location from metadata.
    String shire = CommonUtils.safeGetParameter(request, SamlIdPConstants.SHIRE);
    if (StringUtils.isBlank(shire)) {
        shire = adaptor.get().getAssertionConsumerService().getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve SP ACS URL for AuthnRequest construction for entityID: [{}]", providerId);
        throw new MessageDecodingException("Unable to resolve SP ACS URL for AuthnRequest construction");
    }
    // The target resource at the SP, or a state token generated by an SP to represent the resource.
    final String target = CommonUtils.safeGetParameter(request, SamlIdPConstants.TARGET);
    // A timestamp to help with stale request detection.
    final String time = CommonUtils.safeGetParameter(request, SamlIdPConstants.TIME);
    final SAMLObjectBuilder builder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    final AuthnRequest authnRequest = (AuthnRequest) builder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(shire);
    final SAMLObjectBuilder isBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    final Issuer issuer = (Issuer) isBuilder.buildObject();
    issuer.setValue(providerId);
    authnRequest.setIssuer(issuer);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    final SAMLObjectBuilder pBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME);
    final NameIDPolicy nameIDPolicy = (NameIDPolicy) pBuilder.buildObject();
    nameIDPolicy.setAllowCreate(Boolean.TRUE);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    if (NumberUtils.isCreatable(time)) {
        authnRequest.setIssueInstant(new DateTime(TimeUnit.SECONDS.convert(Long.parseLong(time), TimeUnit.MILLISECONDS), ISOChronology.getInstanceUTC()));
    } else {
        authnRequest.setIssueInstant(new DateTime(DateTime.now(), ISOChronology.getInstanceUTC()));
    }
    authnRequest.setForceAuthn(Boolean.FALSE);
    if (StringUtils.isNotBlank(target)) {
        request.setAttribute(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, target);
    }
    final MessageContext ctx = new MessageContext();
    ctx.setAutoCreateSubcontexts(true);
    if (adaptor.get().isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, adaptor.get(), response, request);
    }
    ctx.setMessage(authnRequest);
    ctx.getSubcontext(SAMLBindingContext.class, true).setHasBindingSignature(false);
    final Pair<SignableSAMLObject, MessageContext> pair = Pair.of(authnRequest, ctx);
    initiateAuthenticationRequest(pair, response, request);
}
Also used : SAMLBindingContext(org.opensaml.saml.common.messaging.context.SAMLBindingContext) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) Issuer(org.opensaml.saml.saml2.core.Issuer) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) DateTime(org.joda.time.DateTime) MessageDecodingException(org.opensaml.messaging.decoder.MessageDecodingException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 12 with AuthnRequest

use of org.opensaml.saml.saml2.core.AuthnRequest 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 13 with AuthnRequest

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

the class SoapResponseCreator method createEcpResponse.

private String createEcpResponse(AuthnRequest authnRequest) throws WSSecurityException {
    ResponseBuilder responseBuilder = new ResponseBuilder();
    org.opensaml.saml.saml2.ecp.Response response = responseBuilder.buildObject();
    response.setSOAP11Actor(HTTP_SCHEMAS_XMLSOAP_ORG_SOAP_ACTOR_NEXT);
    response.setSOAP11MustUnderstand(true);
    response.setAssertionConsumerServiceURL(getAssertionConsumerServiceURL(authnRequest));
    return convertXmlObjectToString(response);
}
Also used : ResponseBuilder(org.opensaml.saml.saml2.ecp.impl.ResponseBuilder)

Example 14 with AuthnRequest

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

the class SoapResponseCreator method createEcpRequestAuthenticated.

private String createEcpRequestAuthenticated(AuthnRequest authnRequest) throws WSSecurityException {
    if (authnRequest.getSignature() != null) {
        RequestAuthenticatedBuilder requestAuthenticatedBuilder = new RequestAuthenticatedBuilder();
        RequestAuthenticated requestAuthenticated = requestAuthenticatedBuilder.buildObject();
        requestAuthenticated.setSOAP11Actor(HTTP_SCHEMAS_XMLSOAP_ORG_SOAP_ACTOR_NEXT);
        return convertXmlObjectToString(requestAuthenticated);
    }
    return "";
}
Also used : RequestAuthenticated(org.opensaml.saml.saml2.ecp.RequestAuthenticated) RequestAuthenticatedBuilder(org.opensaml.saml.saml2.ecp.impl.RequestAuthenticatedBuilder)

Example 15 with AuthnRequest

use of org.opensaml.saml.saml2.core.AuthnRequest 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)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)15 IOException (java.io.IOException)9 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)7 SimpleSign (ddf.security.samlp.SimpleSign)4 XMLObject (org.opensaml.core.xml.XMLObject)4 Document (org.w3c.dom.Document)4 ValidationException (ddf.security.samlp.ValidationException)3 SecurityServiceException (ddf.security.service.SecurityServiceException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 SecureRandom (java.security.SecureRandom)3 ZonedDateTime (java.time.ZonedDateTime)3 ServletException (javax.servlet.ServletException)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)3 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)3 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)3 MessageContext (org.opensaml.messaging.context.MessageContext)3 InputStreamReader (java.io.InputStreamReader)2 Path (javax.ws.rs.Path)2 NewCookie (javax.ws.rs.core.NewCookie)2