Search in sources :

Example 1 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class InitialFlowSetupAction method configureWebflowContextForService.

private void configureWebflowContextForService(final RequestContext context) {
    final Service service = WebUtils.getService(this.argumentExtractors, context);
    if (service != null) {
        LOGGER.debug("Placing service in context scope: [{}]", service.getId());
        final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
        if (registeredService != null && registeredService.getAccessStrategy().isServiceAccessAllowed()) {
            LOGGER.debug("Placing registered service [{}] with id [{}] in context scope", registeredService.getServiceId(), registeredService.getId());
            WebUtils.putRegisteredService(context, registeredService);
            final RegisteredServiceAccessStrategy accessStrategy = registeredService.getAccessStrategy();
            if (accessStrategy.getUnauthorizedRedirectUrl() != null) {
                LOGGER.debug("Placing registered service's unauthorized redirect url [{}] with id [{}] in context scope", accessStrategy.getUnauthorizedRedirectUrl(), registeredService.getServiceId());
                WebUtils.putUnauthorizedRedirectUrl(context, accessStrategy.getUnauthorizedRedirectUrl());
            }
        }
    } else if (!casProperties.getSso().isMissingService()) {
        LOGGER.warn("No service authentication request is available at [{}]. CAS is configured to disable the flow.", WebUtils.getHttpServletRequest(context).getRequestURL());
        throw new NoSuchFlowExecutionException(context.getFlowExecutionContext().getKey(), new UnauthorizedServiceException("screen.service.required.message", "Service is required"));
    }
    WebUtils.putService(context, service);
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) RegisteredServiceAccessStrategy(org.apereo.cas.services.RegisteredServiceAccessStrategy) NoSuchFlowExecutionException(org.springframework.webflow.execution.repository.NoSuchFlowExecutionException)

Example 2 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class GatewayServicesManagementCheck method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final Service service = WebUtils.getService(context);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    if (registeredService == null) {
        final String msg = String.format("Service Management: Unauthorized Service Access. " + "Service [%s] does not match entries in service registry.", service.getId());
        LOGGER.warn(msg);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
    }
    if (!registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        final String msg = String.format("Service Management: Access to service [%s] " + "is disabled by the service registry.", service.getId());
        LOGGER.warn(msg);
        WebUtils.putUnauthorizedRedirectUrlIntoFlowScope(context, registeredService.getAccessStrategy().getUnauthorizedRedirectUrl());
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, msg);
    }
    return success();
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) RegisteredService(org.apereo.cas.services.RegisteredService) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 3 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException 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 UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class AbstractSamlProfileHandlerController method buildSamlResponse.

/**
     * Build saml response.
     *
     * @param response              the response
     * @param request               the request
     * @param authenticationContext the authentication context
     * @param casAssertion          the cas assertion
     */
protected void buildSamlResponse(final HttpServletResponse response, final HttpServletRequest request, final Pair<AuthnRequest, MessageContext> authenticationContext, final Assertion casAssertion) {
    final String issuer = SamlIdPUtils.getIssuerFromSamlRequest(authenticationContext.getKey());
    LOGGER.debug("Located issuer [{}] from authentication context", issuer);
    final SamlRegisteredService registeredService = verifySamlRegisteredService(issuer);
    final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(registeredService, authenticationContext.getKey());
    if (!adaptor.isPresent()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
    }
    LOGGER.debug("Preparing SAML response for [{}]", adaptor.get().getEntityId());
    this.responseBuilder.build(authenticationContext.getKey(), request, response, casAssertion, registeredService, adaptor.get());
    LOGGER.info("Built the SAML response for [{}]", adaptor.get().getEntityId());
}
Also used : SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 5 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException 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);
    if (StringUtils.isBlank(shire)) {
        shire = adaptor.get().getAssertionConsumerService().getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve SP ACS 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 (adaptor.get().isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, adaptor.get(), response, request);
    }
    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) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)19 Service (org.apereo.cas.authentication.principal.Service)8 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)7 RegisteredService (org.apereo.cas.services.RegisteredService)7 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)5 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)4 Authentication (org.apereo.cas.authentication.Authentication)2 RegexRegisteredService (org.apereo.cas.services.RegexRegisteredService)2 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)2 SamlMetadataUIInfo (org.apereo.cas.support.saml.mdui.SamlMetadataUIInfo)2 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)2 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)2 UserProfile (org.pac4j.core.profile.UserProfile)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 ByteSource (com.google.common.io.ByteSource)1 StringWriter (java.io.StringWriter)1 SecureRandom (java.security.SecureRandom)1 ZonedDateTime (java.time.ZonedDateTime)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1