Search in sources :

Example 6 with Issuer

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

the class IdpEndpoint method continueLogout.

private Response continueLogout(LogoutState logoutState, Cookie cookie, SamlProtocol.Binding incomingBinding) throws IdpException {
    if (logoutState == null) {
        throw new IdpException("Cannot continue a Logout that doesn't exist!");
    }
    try {
        SignableSAMLObject logoutObject;
        String relay = "";
        String entityId = "";
        SamlProtocol.Type samlType;
        Optional<String> nextTarget = logoutState.getNextTarget();
        if (nextTarget.isPresent()) {
            // Another target exists, log them out
            entityId = nextTarget.get();
            if (logoutState.getOriginalIssuer().equals(entityId)) {
                return continueLogout(logoutState, cookie, incomingBinding);
            }
            LogoutRequest logoutRequest = logoutMessage.buildLogoutRequest(logoutState.getNameId(), SystemBaseUrl.constructUrl("/idp/logout", true));
            logoutState.setCurrentRequestId(logoutRequest.getID());
            logoutObject = logoutRequest;
            samlType = SamlProtocol.Type.REQUEST;
            relay = "";
        } else {
            // No more targets, respond to original issuer
            entityId = logoutState.getOriginalIssuer();
            String status = logoutState.isPartialLogout() ? StatusCode.PARTIAL_LOGOUT : StatusCode.SUCCESS;
            logoutObject = logoutMessage.buildLogoutResponse(SystemBaseUrl.constructUrl("/idp/logout", true), status, logoutState.getOriginalRequestId());
            relay = logoutState.getInitialRelayState();
            LogoutState decode = logoutStates.decode(cookie.getValue(), true);
            samlType = SamlProtocol.Type.RESPONSE;
        }
        LOGGER.debug("Responding to [{}] with a [{}] and relay state [{}]", entityId, samlType, relay);
        EntityInformation.ServiceInfo entityServiceInfo = serviceProviders.get(entityId).getLogoutService(incomingBinding);
        if (entityServiceInfo == null) {
            LOGGER.info("Could not find entity service info for {}", entityId);
            return continueLogout(logoutState, cookie, incomingBinding);
        }
        switch(entityServiceInfo.getBinding()) {
            case HTTP_REDIRECT:
                return getSamlRedirectResponse(logoutObject, entityServiceInfo.getUrl(), relay, samlType);
            case HTTP_POST:
                return getSamlPostResponse(logoutObject, entityServiceInfo.getUrl(), relay, samlType);
            default:
                LOGGER.debug("No supported binding available for SP [{}].", entityId);
                logoutState.setPartialLogout(true);
                return continueLogout(logoutState, cookie, incomingBinding);
        }
    } catch (WSSecurityException | SimpleSign.SignatureException | IOException e) {
        LOGGER.debug("Error while processing logout", e);
    }
    throw new IdpException("Server error while processing logout");
}
Also used : WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) SamlProtocol(ddf.security.samlp.SamlProtocol) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) EntityInformation(ddf.security.samlp.impl.EntityInformation) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest)

Example 7 with Issuer

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

the class LoginFilter method createIssuer.

/**
     * Creates the issuer object for the response.
     *
     * @param issuerValue
     * @return Issuer
     */
private static Issuer createIssuer(String issuerValue) {
    if (issuerBuilder == null) {
        issuerBuilder = (SAMLObjectBuilder<Issuer>) builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    }
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(issuerValue);
    return issuer;
}
Also used : Issuer(org.opensaml.saml.saml2.core.Issuer)

Example 8 with Issuer

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

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

Example 10 with Issuer

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

the class ECPProfileHandlerController method handleEcpRequest.

/**
 * Handle ecp request.
 *
 * @param response    the response
 * @param request     the request
 * @param soapContext the soap context
 * @param credential  the credential
 * @param binding     the binding
 */
protected void handleEcpRequest(final HttpServletResponse response, final HttpServletRequest request, final MessageContext soapContext, final Credential credential, final String binding) {
    LOGGER.debug("Handling ECP request for SOAP context [{}]", soapContext);
    final Envelope envelope = soapContext.getSubcontext(SOAP11Context.class).getEnvelope();
    SamlUtils.logSamlObject(configBean, envelope);
    final AuthnRequest authnRequest = (AuthnRequest) soapContext.getMessage();
    final Pair<AuthnRequest, MessageContext> authenticationContext = Pair.of(authnRequest, soapContext);
    try {
        LOGGER.debug("Verifying ECP authentication request [{}]", authnRequest);
        final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> serviceRequest = verifySamlAuthenticationRequest(authenticationContext, request);
        LOGGER.debug("Attempting to authenticate ECP request for credential id [{}]", credential.getId());
        final Authentication authentication = authenticateEcpRequest(credential, authenticationContext);
        LOGGER.debug("Authenticated [{}] successfully with authenticated principal [{}]", credential.getId(), authentication.getPrincipal());
        LOGGER.debug("Building ECP SAML response for [{}]", credential.getId());
        final String issuer = SamlIdPUtils.getIssuerFromSamlRequest(authnRequest);
        final Service service = webApplicationServiceFactory.createService(issuer);
        final Assertion casAssertion = buildCasAssertion(authentication, service, serviceRequest.getKey(), new LinkedHashMap<>());
        LOGGER.debug("CAS assertion to use for building ECP SAML response is [{}]", casAssertion);
        buildSamlResponse(response, request, authenticationContext, casAssertion, binding);
    } catch (final AuthenticationException e) {
        LOGGER.error(e.getMessage(), e);
        final String error = e.getHandlerErrors().values().stream().map(Throwable::getMessage).filter(Objects::nonNull).collect(Collectors.joining(","));
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, error));
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, e.getMessage()));
    }
}
Also used : AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Assertion(org.jasig.cas.client.validation.Assertion) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Service(org.apereo.cas.authentication.principal.Service) Envelope(org.opensaml.soap.soap11.Envelope) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SOAP11Context(org.opensaml.soap.messaging.context.SOAP11Context) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Authentication(org.apereo.cas.authentication.Authentication) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Objects(java.util.Objects) MessageContext(org.opensaml.messaging.context.MessageContext)

Aggregations

Issuer (org.opensaml.saml.saml2.core.Issuer)79 Response (org.opensaml.saml.saml2.core.Response)59 DateTime (org.joda.time.DateTime)57 Test (org.junit.jupiter.api.Test)37 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)36 Element (org.w3c.dom.Element)34 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)32 lombok.val (lombok.val)28 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 Document (org.w3c.dom.Document)25 Status (org.opensaml.saml.saml2.core.Status)24 Assertion (org.opensaml.saml.saml2.core.Assertion)22 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)20 SubjectConfirmationDataBean (org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean)20 SAMLObjectBuilder (org.opensaml.saml.common.SAMLObjectBuilder)17 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)16 InputStream (java.io.InputStream)15 IssuerBuilder (org.opensaml.saml.saml2.core.impl.IssuerBuilder)15 Crypto (org.apache.wss4j.common.crypto.Crypto)14 KeyStore (java.security.KeyStore)13