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);
}
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();
}
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;
}
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());
}
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);
}
Aggregations