Search in sources :

Example 21 with Response

use of org.opensaml.saml.saml2.core.Response in project verify-hub by alphagov.

the class CountryAuthnResponseTranslatorServiceTest method setup.

@Before
public void setup() throws Exception {
    IdaSamlBootstrap.bootstrap();
    service = new CountryAuthnResponseTranslatorService(stringToOpenSamlResponseTransformer, responseFromCountryValidator, new IdpIdaStatusUnmarshaller(new IdpIdaStatus.IdpIdaStatusFactory(), new SamlStatusToIdpIdaStatusMappingsFactory()), responseAssertionsFromCountryValidator, validateSamlResponseIssuedByIdpDestination, assertionDecrypter, assertionBlobEncrypter, samlResponseSignatureValidator, samlAssertionsSignatureValidator, new PassthroughAssertionUnmarshaller(new XmlObjectToBase64EncodedStringTransformer<>(), new AuthnContextFactory()));
    Response eidasSAMLResponse = (Response) buildResponseFromFile();
    ValidatedResponse validateEIDASSAMLResponse = new ValidatedResponse(eidasSAMLResponse);
    List<Assertion> decryptedAssertions = eidasSAMLResponse.getAssertions();
    when(samlAuthnResponseTranslatorDto.getSamlResponse()).thenReturn("eidas");
    when(samlAuthnResponseTranslatorDto.getMatchingServiceEntityId()).thenReturn("mid");
    when(stringToOpenSamlResponseTransformer.apply("eidas")).thenReturn(eidasSAMLResponse);
    doNothing().when(responseFromCountryValidator).validate(eidasSAMLResponse);
    when(samlResponseSignatureValidator.validate(eidasSAMLResponse, IDPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(validateEIDASSAMLResponse);
    when(assertionDecrypter.decryptAssertions(validateEIDASSAMLResponse)).thenReturn(decryptedAssertions);
    when(assertionBlobEncrypter.encryptAssertionBlob(eq("mid"), any(String.class))).thenReturn(identityUnderlyingAssertionBlob);
    when(samlAssertionsSignatureValidator.validate(decryptedAssertions, IDPSSODescriptor.DEFAULT_ELEMENT_NAME)).thenReturn(new ValidatedAssertions(decryptedAssertions));
}
Also used : IdpIdaStatus(uk.gov.ida.saml.hub.domain.IdpIdaStatus) Assertion(org.opensaml.saml.saml2.core.Assertion) ValidatedResponse(uk.gov.ida.saml.security.validators.ValidatedResponse) ValidatedResponse(uk.gov.ida.saml.security.validators.ValidatedResponse) Response(org.opensaml.saml.saml2.core.Response) PassthroughAssertionUnmarshaller(uk.gov.ida.saml.hub.transformers.inbound.PassthroughAssertionUnmarshaller) IdpIdaStatusUnmarshaller(uk.gov.ida.saml.hub.transformers.inbound.IdpIdaStatusUnmarshaller) ValidatedAssertions(uk.gov.ida.saml.security.validators.ValidatedAssertions) AuthnContextFactory(uk.gov.ida.saml.core.transformers.AuthnContextFactory) SamlStatusToIdpIdaStatusMappingsFactory(uk.gov.ida.saml.hub.transformers.inbound.SamlStatusToIdpIdaStatusMappingsFactory) Before(org.junit.Before)

Example 22 with Response

use of org.opensaml.saml.saml2.core.Response in project verify-hub by alphagov.

the class CountryAuthnResponseTranslatorService method toModel.

private InboundResponseFromCountry toModel(ValidatedResponse response, Optional<Assertion> validatedIdentityAssertionOptional, String matchingServiceEntityId) {
    Optional<PassthroughAssertion> passthroughAssertion = validatedIdentityAssertionOptional.map(validatedIdentityAssertion -> passthroughAssertionUnmarshaller.fromAssertion(validatedIdentityAssertion, true));
    Optional<LevelOfAssurance> levelOfAssurance = passthroughAssertion.flatMap(assertion -> assertion.getAuthnContext()).map(AuthnContext::name).filter(string -> !isNullOrEmpty(string)).map(LevelOfAssurance::valueOf);
    IdpIdaStatus status = statusUnmarshaller.fromSaml(response.getStatus());
    return new InboundResponseFromCountry(response.getIssuer().getValue(), validatedIdentityAssertionOptional.map(Assertion::getSubject).map(Subject::getNameID).map(NameID::getValue), Optional.ofNullable(status).map(IdpIdaStatus::getStatusCode).map(IdpIdaStatus.Status::name), status.getMessage(), passthroughAssertion.map(assertion -> assertionBlobEncrypter.encryptAssertionBlob(matchingServiceEntityId, assertion.getUnderlyingAssertionBlob())), levelOfAssurance);
}
Also used : LevelOfAssurance(uk.gov.ida.hub.samlengine.domain.LevelOfAssurance) StringToOpenSamlObjectTransformer(uk.gov.ida.saml.deserializers.StringToOpenSamlObjectTransformer) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) Subject(org.opensaml.saml.saml2.core.Subject) IdpIdaStatusUnmarshaller(uk.gov.ida.saml.hub.transformers.inbound.IdpIdaStatusUnmarshaller) ValidatedResponse(uk.gov.ida.saml.security.validators.ValidatedResponse) MdcHelper(uk.gov.ida.hub.samlengine.logging.MdcHelper) ResponseFromCountryValidator(uk.gov.ida.hub.samlengine.validation.country.ResponseFromCountryValidator) SamlResponseSignatureValidator(uk.gov.ida.saml.security.validators.signature.SamlResponseSignatureValidator) Inject(javax.inject.Inject) Assertion(org.opensaml.saml.saml2.core.Assertion) AssertionBlobEncrypter(uk.gov.ida.saml.core.transformers.outbound.decorators.AssertionBlobEncrypter) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) AuthnContext(uk.gov.ida.saml.core.domain.AuthnContext) ResponseAssertionsFromCountryValidator(uk.gov.ida.hub.samlengine.validation.country.ResponseAssertionsFromCountryValidator) Response(org.opensaml.saml.saml2.core.Response) PassthroughAssertionUnmarshaller(uk.gov.ida.saml.hub.transformers.inbound.PassthroughAssertionUnmarshaller) AssertionDecrypter(uk.gov.ida.saml.security.AssertionDecrypter) SamlAuthnResponseTranslatorDto(uk.gov.ida.hub.samlengine.contracts.SamlAuthnResponseTranslatorDto) InboundResponseFromCountry(uk.gov.ida.hub.samlengine.domain.InboundResponseFromCountry) List(java.util.List) PassthroughAssertion(uk.gov.ida.saml.core.domain.PassthroughAssertion) LevelOfAssurance(uk.gov.ida.hub.samlengine.domain.LevelOfAssurance) DestinationValidator(uk.gov.ida.saml.core.validators.DestinationValidator) Optional(java.util.Optional) IdpIdaStatus(uk.gov.ida.saml.hub.domain.IdpIdaStatus) NameID(org.opensaml.saml.saml2.core.NameID) SamlAssertionsSignatureValidator(uk.gov.ida.saml.security.SamlAssertionsSignatureValidator) InboundResponseFromCountry(uk.gov.ida.hub.samlengine.domain.InboundResponseFromCountry) PassthroughAssertion(uk.gov.ida.saml.core.domain.PassthroughAssertion) IdpIdaStatus(uk.gov.ida.saml.hub.domain.IdpIdaStatus) Subject(org.opensaml.saml.saml2.core.Subject) AuthnContext(uk.gov.ida.saml.core.domain.AuthnContext)

Example 23 with Response

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

the class Saml2AttributeQueryProfileHandlerController method handlePostRequest.

/**
 * Handle post request.
 *
 * @param response the response
 * @param request  the request
 */
@PostMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SOAP_ATTRIBUTE_QUERY)
protected void handlePostRequest(final HttpServletResponse response, final HttpServletRequest request) {
    final MessageContext ctx = decodeSoapRequest(request);
    final AttributeQuery query = (AttributeQuery) ctx.getMessage();
    try {
        final String issuer = query.getIssuer().getValue();
        final SamlRegisteredService service = verifySamlRegisteredService(issuer);
        final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(service, query);
        if (!adaptor.isPresent()) {
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
        }
        final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
        verifyAuthenticationContextSignature(ctx, request, query, facade);
        final Map<String, Object> attrs = new LinkedHashMap<>();
        if (query.getAttributes().isEmpty()) {
            final String id = this.samlAttributeQueryTicketFactory.createTicketIdFor(query.getSubject().getNameID().getValue());
            final SamlAttributeQueryTicket ticket = this.ticketRegistry.getTicket(id, SamlAttributeQueryTicket.class);
            final Authentication authentication = ticket.getTicketGrantingTicket().getAuthentication();
            final Principal principal = authentication.getPrincipal();
            final Map<String, Object> authnAttrs = authentication.getAttributes();
            final Map<String, Object> principalAttrs = principal.getAttributes();
            query.getAttributes().forEach(a -> {
                if (authnAttrs.containsKey(a.getName())) {
                    attrs.put(a.getName(), authnAttrs.get(a.getName()));
                } else if (principalAttrs.containsKey(a.getName())) {
                    attrs.put(a.getName(), principalAttrs.get(a.getName()));
                }
            });
        }
        final Assertion casAssertion = buildCasAssertion(issuer, service, attrs);
        this.responseBuilder.build(query, request, response, casAssertion, service, facade, SAMLConstants.SAML2_SOAP11_BINDING_URI);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        request.setAttribute(SamlIdPConstants.REQUEST_ATTRIBUTE_ERROR, e.getMessage());
        samlFaultResponseBuilder.build(query, request, response, null, null, null, SAMLConstants.SAML2_SOAP11_BINDING_URI);
    }
}
Also used : SamlAttributeQueryTicket(org.apereo.cas.ticket.query.SamlAttributeQueryTicket) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Assertion(org.jasig.cas.client.validation.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) LinkedHashMap(java.util.LinkedHashMap) AttributeQuery(org.opensaml.saml.saml2.core.AttributeQuery) Authentication(org.apereo.cas.authentication.Authentication) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SAMLObject(org.opensaml.saml.common.SAMLObject) MessageContext(org.opensaml.messaging.context.MessageContext) Principal(org.apereo.cas.authentication.principal.Principal) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 24 with Response

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

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

the class AbstractSamlProfileHandlerController method constructServiceUrl.

/**
 * Construct service url string.
 *
 * @param request  the request
 * @param response the response
 * @param pair     the pair
 * @return the string
 * @throws SamlException the saml exception
 */
@SneakyThrows
protected String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final Pair<? extends SignableSAMLObject, MessageContext> pair) throws SamlException {
    final AuthnRequest authnRequest = AuthnRequest.class.cast(pair.getLeft());
    final MessageContext messageContext = pair.getRight();
    try (StringWriter writer = SamlUtils.transformSamlObject(this.configBean, authnRequest)) {
        final URLBuilder builder = new URLBuilder(this.callbackService.getId());
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_ENTITY_ID, SamlIdPUtils.getIssuerFromSamlRequest(authnRequest)));
        final String samlRequest = EncodingUtils.encodeBase64(writer.toString().getBytes(StandardCharsets.UTF_8));
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_REQUEST, samlRequest));
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, SAMLBindingSupport.getRelayState(messageContext)));
        final String url = builder.buildURL();
        LOGGER.trace("Built service callback url [{}]", url);
        return CommonUtils.constructServiceUrl(request, response, url, casProperties.getServer().getName(), CasProtocolConstants.PARAMETER_SERVICE, CasProtocolConstants.PARAMETER_TICKET, false);
    }
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) StringWriter(java.io.StringWriter) MessageContext(org.opensaml.messaging.context.MessageContext) URLBuilder(net.shibboleth.utilities.java.support.net.URLBuilder) SneakyThrows(lombok.SneakyThrows)

Aggregations

Response (org.opensaml.saml.saml2.core.Response)241 Test (org.junit.jupiter.api.Test)183 ResponseBuilder.aResponse (uk.gov.ida.saml.core.test.builders.ResponseBuilder.aResponse)94 Assertion (org.opensaml.saml.saml2.core.Assertion)82 EncryptedAssertion (org.opensaml.saml.saml2.core.EncryptedAssertion)61 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)52 Element (org.w3c.dom.Element)51 Status (org.opensaml.saml.saml2.core.Status)50 Document (org.w3c.dom.Document)43 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)42 DateTime (org.joda.time.DateTime)42 Response (javax.ws.rs.core.Response)38 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)34 lombok.val (lombok.val)32 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)30 Issuer (org.opensaml.saml.saml2.core.Issuer)30 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)27 Test (org.junit.Test)26 IOException (java.io.IOException)25 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)24