Search in sources :

Example 1 with Assertion

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

the class WsFederationHelper method parseTokenFromString.

/**
     * parseTokenFromString converts a raw wresult and extracts it into an assertion.
     *
     * @param wresult the raw token returned by the IdP
     * @param config  the config
     * @return an assertion
     */
public Assertion parseTokenFromString(final String wresult, final WsFederationConfiguration config) {
    LOGGER.debug("Result token received from ADFS is [{}]", wresult);
    try (InputStream in = new ByteArrayInputStream(wresult.getBytes(StandardCharsets.UTF_8))) {
        LOGGER.debug("Parsing token into a document");
        final Document document = configBean.getParserPool().parse(in);
        final Element metadataRoot = document.getDocumentElement();
        final UnmarshallerFactory unmarshallerFactory = configBean.getUnmarshallerFactory();
        final Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(metadataRoot);
        if (unmarshaller == null) {
            throw new IllegalArgumentException("Unmarshaller for the metadata root element cannot be determined");
        }
        LOGGER.debug("Unmarshalling the document into a security token response");
        final RequestSecurityTokenResponse rsToken = (RequestSecurityTokenResponse) unmarshaller.unmarshall(metadataRoot);
        if (rsToken == null || rsToken.getRequestedSecurityToken() == null) {
            throw new IllegalArgumentException("Request security token response is null");
        }
        //Get our SAML token
        LOGGER.debug("Locating list of requested security tokens");
        final List<RequestedSecurityToken> rst = rsToken.getRequestedSecurityToken();
        if (rst.isEmpty()) {
            throw new IllegalArgumentException("No requested security token response is provided in the response");
        }
        LOGGER.debug("Locating the first occurrence of a requested security token in the list");
        final RequestedSecurityToken reqToken = rst.get(0);
        if (reqToken.getSecurityTokens() == null || reqToken.getSecurityTokens().isEmpty()) {
            throw new IllegalArgumentException("Requested security token response is not carrying any security tokens");
        }
        Assertion assertion = null;
        LOGGER.debug("Locating the first occurrence of a security token from the requested security token");
        XMLObject securityToken = reqToken.getSecurityTokens().get(0);
        if (securityToken instanceof EncryptedData) {
            try {
                LOGGER.debug("Security token is encrypted. Attempting to decrypt to extract the assertion");
                final EncryptedData encryptedData = EncryptedData.class.cast(securityToken);
                final Decrypter decrypter = buildAssertionDecrypter(config);
                LOGGER.debug("Built an instance of [{}]", decrypter.getClass().getName());
                securityToken = decrypter.decryptData(encryptedData);
            } catch (final Exception e) {
                throw new IllegalArgumentException("Unable to decrypt security token", e);
            }
        }
        if (securityToken instanceof Assertion) {
            LOGGER.debug("Security token is an assertion.");
            assertion = Assertion.class.cast(securityToken);
        }
        if (assertion == null) {
            throw new IllegalArgumentException("Could not extract or decrypt an assertion based on the security token provided");
        }
        LOGGER.debug("Extracted assertion successfully: [{}]", assertion);
        return assertion;
    } catch (final Exception ex) {
        LOGGER.warn(ex.getMessage());
        return null;
    }
}
Also used : RequestedSecurityToken(org.opensaml.soap.wsfed.RequestedSecurityToken) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Assertion(org.opensaml.saml.saml1.core.Assertion) XMLObject(org.opensaml.core.xml.XMLObject) Decrypter(org.opensaml.saml.saml2.encryption.Decrypter) UnmarshallerFactory(org.opensaml.core.xml.io.UnmarshallerFactory) Document(org.w3c.dom.Document) SignatureException(org.opensaml.xmlsec.signature.support.SignatureException) SecurityException(org.opensaml.security.SecurityException) ByteArrayInputStream(java.io.ByteArrayInputStream) EncryptedData(org.opensaml.xmlsec.encryption.EncryptedData) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) RequestSecurityTokenResponse(org.opensaml.soap.wsfed.RequestSecurityTokenResponse)

Example 2 with Assertion

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

the class WsFederationHelperTests method verifyValidateSignatureBadKey.

@Test
@DirtiesContext
public void verifyValidateSignatureBadKey() throws Exception {
    final List<Credential> signingWallet = new ArrayList<>();
    final WsFederationConfiguration cfg = new WsFederationConfiguration();
    cfg.setSigningCertificateResources(ctx.getResource("classpath:bad-signing.crt"));
    signingWallet.addAll(cfg.getSigningCertificates());
    final String wresult = testTokens.get(GOOD_TOKEN);
    final Assertion assertion = wsFederationHelper.parseTokenFromString(wresult, wsFedConfig);
    wsFedConfig.getSigningCertificates().clear();
    wsFedConfig.getSigningCertificates().addAll(signingWallet);
    final boolean result = wsFederationHelper.validateSignature(assertion, wsFedConfig);
    assertFalse("testValidateSignatureModifiedKey() - False", result);
}
Also used : Credential(org.opensaml.security.credential.Credential) WsFederationCredential(org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential) ArrayList(java.util.ArrayList) Assertion(org.opensaml.saml.saml1.core.Assertion) Test(org.junit.Test) DirtiesContext(org.springframework.test.annotation.DirtiesContext)

Example 3 with Assertion

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

the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.

/**
     * Construct SAML response.
     * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
     *
     * @param service the service
     * @return the SAML response
     */
protected String constructSamlResponse(final GoogleAccountsService service) {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(service.getPrincipal(), service);
    final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, service.getId(), service);
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    final String sessionIndex = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
    final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
    assertion.setConditions(conditions);
    final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId());
    assertion.setSubject(subject);
    response.getAssertions().add(assertion);
    final StringWriter writer = new StringWriter();
    this.samlObjectBuilder.marshalSamlXmlObject(response, writer);
    final String result = writer.toString();
    LOGGER.debug("Generated Google SAML response: [{}]", result);
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Assertion(org.opensaml.saml.saml2.core.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) SecureRandom(java.security.SecureRandom) Conditions(org.opensaml.saml.saml2.core.Conditions) Subject(org.opensaml.saml.saml2.core.Subject) StringWriter(java.io.StringWriter) ZonedDateTime(java.time.ZonedDateTime) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement)

Example 4 with Assertion

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

the class BaseSamlProfileSamlResponseBuilder method build.

@Override
public T build(final AuthnRequest authnRequest, final HttpServletRequest request, final HttpServletResponse response, final org.jasig.cas.client.validation.Assertion casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final Assertion assertion = buildSamlAssertion(authnRequest, request, response, casAssertion, service, adaptor);
    final T finalResponse = buildResponse(assertion, casAssertion, authnRequest, service, adaptor, request, response);
    return encodeFinalResponse(request, response, service, adaptor, finalResponse);
}
Also used : EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion)

Example 5 with Assertion

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

the class SamlProfileSaml2ResponseBuilder method buildResponse.

@Override
protected Response buildResponse(final Assertion assertion, final org.jasig.cas.client.validation.Assertion casAssertion, final AuthnRequest authnRequest, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final HttpServletRequest request, final HttpServletResponse response) throws SamlException {
    final String id = '_' + String.valueOf(Math.abs(new SecureRandom().nextLong()));
    Response samlResponse = newResponse(id, ZonedDateTime.now(ZoneOffset.UTC), authnRequest.getID(), null);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    samlResponse.setIssuer(buildEntityIssuer());
    samlResponse.setConsent(RequestAbstractType.UNSPECIFIED_CONSENT);
    final SAMLObject finalAssertion = encryptAssertion(assertion, request, response, service, adaptor);
    if (finalAssertion instanceof EncryptedAssertion) {
        LOGGER.debug("Built assertion is encrypted, so the response will add it to the encrypted assertions collection");
        samlResponse.getEncryptedAssertions().add(EncryptedAssertion.class.cast(finalAssertion));
    } else {
        LOGGER.debug("Built assertion is not encrypted, so the response will add it to the assertions collection");
        samlResponse.getAssertions().add(Assertion.class.cast(finalAssertion));
    }
    final Status status = newStatus(StatusCode.SUCCESS, StatusCode.SUCCESS);
    samlResponse.setStatus(status);
    SamlUtils.logSamlObject(this.configBean, samlResponse);
    if (service.isSignResponses()) {
        LOGGER.debug("SAML entity id [{}] indicates that SAML responses should be signed", adaptor.getEntityId());
        samlResponse = this.samlObjectSigner.encode(samlResponse, service, adaptor, response, request);
    }
    return samlResponse;
}
Also used : Response(org.opensaml.saml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Status(org.opensaml.saml.saml2.core.Status) SAMLObject(org.opensaml.saml.common.SAMLObject) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) EncryptedAssertion(org.opensaml.saml.saml2.core.EncryptedAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) SecureRandom(java.security.SecureRandom)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)175 Test (org.junit.jupiter.api.Test)118 Response (org.opensaml.saml.saml2.core.Response)62 AssertionBuilder.anAssertion (uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion)61 EncryptedAssertion (org.opensaml.saml.saml2.core.EncryptedAssertion)58 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)43 Attribute (org.opensaml.saml.saml2.core.Attribute)25 DateTime (org.joda.time.DateTime)23 Element (org.w3c.dom.Element)22 NameID (org.opensaml.saml.saml2.core.NameID)20 XMLObject (org.opensaml.core.xml.XMLObject)19 PassthroughAssertion (uk.gov.ida.saml.core.domain.PassthroughAssertion)17 ValidatedResponse (uk.gov.ida.saml.security.validators.ValidatedResponse)15 Authentication (org.springframework.security.core.Authentication)14 SubjectConfirmation (org.opensaml.saml.saml2.core.SubjectConfirmation)13 Test (org.junit.Test)12 AuthnStatement (org.opensaml.saml.saml2.core.AuthnStatement)12 Conditions (org.opensaml.saml.saml2.core.Conditions)12 NameIDBuilder (org.opensaml.saml.saml2.core.impl.NameIDBuilder)11 Saml2ResponseValidatorResult (org.springframework.security.saml2.core.Saml2ResponseValidatorResult)11