Search in sources :

Example 26 with Assertion

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

the class SSOSamlProfileCallbackHandlerController method validateRequestAndBuildCasAssertion.

private Assertion validateRequestAndBuildCasAssertion(final HttpServletResponse response, final HttpServletRequest request, final Pair<AuthnRequest, MessageContext> pair) throws Exception {
    final AuthnRequest authnRequest = pair.getKey();
    final String ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
    this.ticketValidator.setRenew(authnRequest.isForceAuthn());
    final String serviceUrl = constructServiceUrl(request, response, pair);
    LOGGER.trace("Created service url for validation: [{}]", serviceUrl);
    final Assertion assertion = this.ticketValidator.validate(ticket, serviceUrl);
    logCasValidationAssertion(assertion);
    return assertion;
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Assertion(org.jasig.cas.client.validation.Assertion)

Example 27 with Assertion

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

the class AbstractSaml20ObjectBuilder method newAssertion.

/**
 * Create a new SAML1 response object.
 *
 * @param authnStatement the authn statement
 * @param issuer         the issuer
 * @param issuedAt       the issued at
 * @param id             the id
 * @return the assertion
 */
public Assertion newAssertion(final List<Statement> authnStatement, final String issuer, final ZonedDateTime issuedAt, final String id) {
    final Assertion assertion = newSamlObject(Assertion.class);
    assertion.setID(id);
    assertion.setIssueInstant(DateTimeUtils.dateTimeOf(issuedAt));
    assertion.setIssuer(newIssuer(issuer));
    assertion.getStatements().addAll(authnStatement);
    return assertion;
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion)

Example 28 with Assertion

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

the class WsFederationHelper method buildAndVerifyAssertion.

/**
 * converts a token into an assertion.
 *
 * @param reqToken the req token
 * @param config   the config
 * @return an assertion
 */
public Pair<Assertion, WsFederationConfiguration> buildAndVerifyAssertion(final RequestedSecurityToken reqToken, final Collection<WsFederationConfiguration> config) {
    final XMLObject securityToken = getSecurityTokenFromRequestedToken(reqToken, config);
    if (securityToken instanceof Assertion) {
        LOGGER.debug("Security token is an assertion.");
        final Assertion assertion = Assertion.class.cast(securityToken);
        LOGGER.debug("Extracted assertion successfully: [{}]", assertion);
        final WsFederationConfiguration cfg = config.stream().filter(c -> c.getIdentityProviderIdentifier().equals(assertion.getIssuer())).findFirst().orElse(null);
        if (cfg == null) {
            throw new IllegalArgumentException("Could not locate wsfed configuration for security token provided. The assertion issuer " + assertion.getIssuer() + "does not match any of the identity provider identifiers defined in the configuration");
        }
        return Pair.of(assertion, cfg);
    }
    throw new IllegalArgumentException("Could not extract or decrypt an assertion based on the security token provided");
}
Also used : Assertion(org.opensaml.saml.saml1.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject)

Example 29 with Assertion

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

the class WsFederationHelperTests method verifyCreateCredentialFromToken.

@Test
public void verifyCreateCredentialFromToken() {
    final String wresult = testTokens.get(GOOD_TOKEN);
    final Pair<Assertion, WsFederationConfiguration> assertion = wsFederationHelper.buildAndVerifyAssertion(wsFederationHelper.getRequestSecurityTokenFromResult(wresult), wsFederationConfigurations);
    final WsFederationCredential expResult = new WsFederationCredential();
    expResult.setIssuedOn(ZonedDateTime.parse("2014-02-26T22:51:16.504Z"));
    expResult.setNotBefore(ZonedDateTime.parse("2014-02-26T22:51:16.474Z"));
    expResult.setNotOnOrAfter(ZonedDateTime.parse("2014-02-26T23:51:16.474Z"));
    expResult.setIssuer("http://adfs.example.com/adfs/services/trust");
    expResult.setAudience("urn:federation:cas");
    expResult.setId("_6257b2bf-7361-4081-ae1f-ec58d4310f61");
    final WsFederationCredential result = wsFederationHelper.createCredentialFromToken(assertion.getKey());
    assertNotNull("testCreateCredentialFromToken() - Not Null", result);
    assertEquals("testCreateCredentialFromToken() - IssuedOn", expResult.getIssuedOn(), result.getIssuedOn());
    assertEquals("testCreateCredentialFromToken() - NotBefore", expResult.getNotBefore(), result.getNotBefore());
    assertEquals("testCreateCredentialFromToken() - NotOnOrAfter", expResult.getNotOnOrAfter(), result.getNotOnOrAfter());
    assertEquals("testCreateCredentialFromToken() - Issuer", expResult.getIssuer(), result.getIssuer());
    assertEquals("testCreateCredentialFromToken() - Audience", expResult.getAudience(), result.getAudience());
    assertEquals("testCreateCredentialFromToken() - Id", expResult.getId(), result.getId());
}
Also used : Assertion(org.opensaml.saml.saml1.core.Assertion) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) Test(org.junit.Test)

Example 30 with Assertion

use of org.opensaml.saml.saml2.core.Assertion 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);
    final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Resolving service provider assertion consumer service URL for [{}] and binding [{}]", providerId, SAMLConstants.SAML2_POST_BINDING_URI);
        @NonNull final AssertionConsumerService acs = facade.getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI);
        shire = acs.getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve service provider assertion consumer service 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 (facade.isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, facade, response, request, SAMLConstants.SAML2_POST_BINDING_URI);
    }
    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) NonNull(lombok.NonNull) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)33 Response (org.opensaml.saml.saml2.core.Response)31 Element (org.w3c.dom.Element)31 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 Document (org.w3c.dom.Document)22 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)20 Status (org.opensaml.saml.saml2.core.Status)20 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)18 DateTime (org.joda.time.DateTime)16 Test (org.junit.Test)16 Assertion (org.opensaml.saml.saml1.core.Assertion)13 InputStream (java.io.InputStream)11 Crypto (org.apache.wss4j.common.crypto.Crypto)11 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)11 ZonedDateTime (java.time.ZonedDateTime)10 XMLObject (org.opensaml.core.xml.XMLObject)10 KeyStore (java.security.KeyStore)9 Merlin (org.apache.wss4j.common.crypto.Merlin)9 Assertion (org.jasig.cas.client.validation.Assertion)9 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)9