Search in sources :

Example 51 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project pac4j by pac4j.

the class SAML2DefaultResponseValidator method validateSamlProtocolResponse.

/**
 * Validates the SAML protocol response:
 * - IssueInstant
 * - Issuer
 * - StatusCode
 * - Signature
 *
 * @param response the response
 * @param context  the context
 * @param engine   the engine
 */
protected final void validateSamlProtocolResponse(final Response response, final SAML2MessageContext context, final SignatureTrustEngine engine) {
    if (!StatusCode.SUCCESS.equals(response.getStatus().getStatusCode().getValue())) {
        String status = response.getStatus().getStatusCode().getValue();
        if (response.getStatus().getStatusMessage() != null) {
            status += " / " + response.getStatus().getStatusMessage().getMessage();
        }
        throw new SAMLException("Authentication response is not success ; actual " + status);
    }
    if (response.getSignature() != null) {
        final String entityId = context.getSAMLPeerEntityContext().getEntityId();
        validateSignature(response.getSignature(), entityId, engine);
        context.getSAMLPeerEntityContext().setAuthenticated(true);
    }
    if (!isIssueInstantValid(response.getIssueInstant())) {
        throw new SAMLIssueInstantException("Response issue instant is too old or in the future");
    }
    AuthnRequest request = null;
    final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
    if (messageStorage != null && response.getInResponseTo() != null) {
        final XMLObject xmlObject = messageStorage.retrieveMessage(response.getInResponseTo());
        if (xmlObject == null) {
            throw new SAMLInResponseToMismatchException("InResponseToField of the Response doesn't correspond to sent message " + response.getInResponseTo());
        } else if (xmlObject instanceof AuthnRequest) {
            request = (AuthnRequest) xmlObject;
        } else {
            throw new SAMLInResponseToMismatchException("Sent request was of different type than the expected AuthnRequest " + response.getInResponseTo());
        }
    }
    verifyEndpoint(context.getSAMLEndpointContext().getEndpoint(), response.getDestination());
    if (request != null) {
        verifyRequest(request, context);
    }
    if (response.getIssuer() != null) {
        validateIssuer(response.getIssuer(), context);
    }
}
Also used : SAMLInResponseToMismatchException(org.pac4j.saml.exceptions.SAMLInResponseToMismatchException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) XMLObject(org.opensaml.core.xml.XMLObject) SAMLIssueInstantException(org.pac4j.saml.exceptions.SAMLIssueInstantException) SAMLMessageStorage(org.pac4j.saml.storage.SAMLMessageStorage) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 52 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project pac4j by pac4j.

the class SAML2RedirectActionBuilder method redirect.

@Override
public RedirectAction redirect(final WebContext wc) {
    final SAML2MessageContext context = this.client.getContextProvider().buildContext(wc);
    final String relayState = this.client.getStateParameter(wc);
    final AuthnRequest authnRequest = this.saml2ObjectBuilder.build(context);
    this.client.getProfileHandler().send(context, authnRequest, relayState);
    final Pac4jSAMLResponse adapter = context.getProfileRequestContextOutboundMessageTransportResponse();
    if (this.client.getConfiguration().getDestinationBindingType().equalsIgnoreCase(SAMLConstants.SAML2_POST_BINDING_URI)) {
        final String content = adapter.getOutgoingContent();
        return RedirectAction.success(content);
    }
    final String location = adapter.getRedirectUrl();
    return RedirectAction.redirect(location);
}
Also used : SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) Pac4jSAMLResponse(org.pac4j.saml.transport.Pac4jSAMLResponse) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest)

Example 53 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project testcases by coheigea.

the class SamlSso method login.

@GET
public javax.ws.rs.core.Response login(@QueryParam("SAMLRequest") String samlRequest, @QueryParam("RelayState") String relayState) throws Exception {
    byte[] deflatedToken = Base64Utility.decode(samlRequest);
    InputStream tokenStream = new DeflateEncoderDecoder().inflateToken(deflatedToken);
    Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
    AuthnRequest request = (AuthnRequest) OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
    System.out.println(DOM2Writer.nodeToString(responseDoc));
    String racs = request.getAssertionConsumerServiceURL();
    String requestIssuer = request.getIssuer().getValue();
    // Match the RACS + Issuer against known values
    boolean match = false;
    if (serviceProviders != null) {
        for (ServiceProvider sp : serviceProviders) {
            if (sp.getIssuer() != null && sp.getIssuer().equals(requestIssuer) && ((sp.getRacs() != null && sp.getRacs().equals(racs)) || sp.getRacs() == null)) {
                match = true;
            }
        }
    }
    if (!match) {
        throw new BadRequestException();
    }
    // Create the response
    Element response = createResponse(request.getID(), racs, requestIssuer);
    String responseStr = encodeResponse(response);
    // Perform Redirect to RACS
    UriBuilder ub = UriBuilder.fromUri(racs);
    ub.queryParam("SAMLResponse", responseStr);
    ub.queryParam("RelayState", relayState);
    return javax.ws.rs.core.Response.seeOther(ub.build()).build();
}
Also used : InputStreamReader(java.io.InputStreamReader) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) BadRequestException(javax.ws.rs.BadRequestException) Document(org.w3c.dom.Document) UriBuilder(javax.ws.rs.core.UriBuilder) DeflateEncoderDecoder(org.apache.cxf.rs.security.saml.DeflateEncoderDecoder) GET(javax.ws.rs.GET)

Example 54 with AuthnRequest

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

the class SAMLUtils method buildAuthnRequestUrl.

public static String buildAuthnRequestUrl(final String authnId, final SAMLProviderMetadata spMetadata, final SAMLProviderMetadata idpMetadata, final String signatureAlgorithm) {
    String redirectUrl = "";
    try {
        DefaultBootstrap.bootstrap();
        AuthnRequest authnRequest = SAMLUtils.buildAuthnRequestObject(authnId, spMetadata.getEntityId(), idpMetadata.getSsoUrl(), spMetadata.getSsoUrl());
        PrivateKey privateKey = null;
        if (spMetadata.getKeyPair() != null) {
            privateKey = spMetadata.getKeyPair().getPrivate();
        }
        redirectUrl = idpMetadata.getSsoUrl() + "?" + SAMLUtils.generateSAMLRequestSignature("SAMLRequest=" + SAMLUtils.encodeSAMLRequest(authnRequest), privateKey, signatureAlgorithm);
    } catch (ConfigurationException | FactoryConfigurationError | MarshallingException | IOException | NoSuchAlgorithmException | InvalidKeyException | java.security.SignatureException e) {
        s_logger.error("SAML AuthnRequest message building error: " + e.getMessage());
    }
    return redirectUrl;
}
Also used : PrivateKey(java.security.PrivateKey) AuthnRequest(org.opensaml.saml2.core.AuthnRequest) MarshallingException(org.opensaml.xml.io.MarshallingException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ConfigurationException(org.opensaml.xml.ConfigurationException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError)

Example 55 with AuthnRequest

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

the class SAMLUtilsTest method testBuildAuthnRequestObject.

@Test
public void testBuildAuthnRequestObject() throws Exception {
    String consumerUrl = "http://someurl.com";
    String idpUrl = "http://idp.domain.example";
    String spId = "cloudstack";
    String authnId = SAMLUtils.generateSecureRandomId();
    AuthnRequest req = SAMLUtils.buildAuthnRequestObject(authnId, spId, idpUrl, consumerUrl);
    assertEquals(req.getAssertionConsumerServiceURL(), consumerUrl);
    assertEquals(req.getDestination(), idpUrl);
    assertEquals(req.getIssuer().getValue(), spId);
}
Also used : AuthnRequest(org.opensaml.saml2.core.AuthnRequest) Test(org.junit.Test)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)63 Test (org.junit.Test)11 Issuer (org.opensaml.saml.saml2.core.Issuer)10 Document (org.w3c.dom.Document)9 AuthnRequestBuilder.anAuthnRequest (uk.gov.ida.saml.core.test.builders.AuthnRequestBuilder.anAuthnRequest)9 RelyingPartyRegistration (org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration)8 DateTime (org.joda.time.DateTime)7 IOException (java.io.IOException)6 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)6 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)6 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)6 XMLObject (org.opensaml.core.xml.XMLObject)6 MessageContext (org.opensaml.messaging.context.MessageContext)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 Response (javax.ws.rs.core.Response)5 Assertion (org.jasig.cas.client.validation.Assertion)5 NameIDPolicy (org.opensaml.saml.saml2.core.NameIDPolicy)5 Element (org.w3c.dom.Element)5 QName (javax.xml.namespace.QName)4 AuthnContextClassRef (org.opensaml.saml.saml2.core.AuthnContextClassRef)4