use of org.opensaml.saml.saml2.core.AuthnRequest in project cas by apereo.
the class AbstractSamlIdPProfileHandlerController method singleSignOnSessionExists.
/**
* Single sign on session exists.
*
* @param pair the pair
* @param request the request
* @param response the response
* @return the boolean
*/
protected Optional<TicketGrantingTicket> singleSignOnSessionExists(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) {
val authnRequest = AuthnRequest.class.cast(pair.getLeft());
if (authnRequest.isForceAuthn()) {
LOGGER.trace("Authentication request asks for forced authn. Ignoring existing single sign-on session, if any");
return Optional.empty();
}
val cookie = configurationContext.getTicketGrantingTicketCookieGenerator().retrieveCookieValue(request);
if (StringUtils.isBlank(cookie)) {
LOGGER.trace("Single sign-on session cannot be found or determined. Ignoring single sign-on session");
return Optional.empty();
}
val ticketGrantingTicket = configurationContext.getTicketRegistrySupport().getTicketGrantingTicket(cookie);
if (ticketGrantingTicket == null) {
LOGGER.debug("Authentication transaction linked to single sign-on session cannot determined.");
return Optional.empty();
}
val authn = ticketGrantingTicket.getAuthentication();
LOGGER.debug("Located single sign-on authentication for principal [{}]", authn.getPrincipal());
val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
val service = configurationContext.getWebApplicationServiceFactory().createService(issuer);
val registeredService = configurationContext.getServicesManager().findServiceBy(service);
val ssoRequest = SingleSignOnParticipationRequest.builder().httpServletRequest(request).build().attribute(Service.class.getName(), service).attribute(RegisteredService.class.getName(), registeredService).attribute(Issuer.class.getName(), issuer).attribute(Authentication.class.getName(), authn).attribute(TicketGrantingTicket.class.getName(), cookie).attribute(AuthnRequest.class.getName(), authnRequest);
val ssoStrategy = configurationContext.getSingleSignOnParticipationStrategy();
LOGGER.debug("Checking for single sign-on participation for issuer [{}]", issuer);
val ssoAvailable = ssoStrategy.supports(ssoRequest) && ssoStrategy.isParticipating(ssoRequest);
return ssoAvailable ? Optional.of(ticketGrantingTicket) : Optional.empty();
}
use of org.opensaml.saml.saml2.core.AuthnRequest in project cas by apereo.
the class AbstractSamlIdPProfileHandlerController method buildResponseBasedSingleSignOnSession.
/**
* Build response based single sign on session.
* The http response before encoding the SAML response is reset
* to ensure a clean slate from previous attempts, specially
* when requests/responses are produced rapidly.
*
* @param context the pair
* @param ticketGrantingTicket the authentication
* @param request the request
* @param response the response
* @throws Exception the exception
*/
protected void buildResponseBasedSingleSignOnSession(final Pair<? extends RequestAbstractType, MessageContext> context, final TicketGrantingTicket ticketGrantingTicket, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
val authnRequest = (AuthnRequest) context.getLeft();
val id = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
val service = configurationContext.getWebApplicationServiceFactory().createService(id);
service.getAttributes().put(SamlProtocolConstants.PARAMETER_ENTITY_ID, CollectionUtils.wrapList(id));
val registeredService = configurationContext.getServicesManager().findServiceBy(service, SamlRegisteredService.class);
val audit = AuditableContext.builder().service(service).authentication(ticketGrantingTicket.getAuthentication()).registeredService(registeredService).httpRequest(request).httpResponse(response).build();
val accessResult = configurationContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
accessResult.throwExceptionIfNeeded();
val assertion = buildCasAssertion(ticketGrantingTicket.getAuthentication(), service, registeredService, Map.of());
val authenticationContext = buildAuthenticationContextPair(request, response, context);
val binding = determineProfileBinding(authenticationContext);
val messageContext = authenticationContext.getRight();
val relayState = SAMLBindingSupport.getRelayState(messageContext);
SAMLBindingSupport.setRelayState(authenticationContext.getRight(), relayState);
response.reset();
val factory = (ServiceTicketFactory) getConfigurationContext().getTicketFactory().get(ServiceTicket.class);
val st = factory.create(ticketGrantingTicket, service, false, ServiceTicket.class);
getConfigurationContext().getTicketRegistry().addTicket(st);
getConfigurationContext().getTicketRegistry().updateTicket(ticketGrantingTicket);
buildSamlResponse(response, request, authenticationContext, assertion, binding);
}
use of org.opensaml.saml.saml2.core.AuthnRequest in project cas by apereo.
the class AbstractSamlIdPProfileHandlerController method verifySamlAuthenticationRequest.
/**
* Verify saml authentication request.
*
* @param authenticationContext the pair
* @param request the request
* @return the pair
* @throws Exception the exception
*/
protected Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> verifySamlAuthenticationRequest(final Pair<? extends RequestAbstractType, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception {
val authnRequest = (AuthnRequest) authenticationContext.getKey();
val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
LOGGER.debug("Located issuer [{}] from authentication request", issuer);
val registeredService = verifySamlRegisteredService(issuer);
LOGGER.debug("Fetching SAML2 metadata adaptor for [{}]", issuer);
val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(configurationContext.getSamlRegisteredServiceCachingMetadataResolver(), registeredService, authnRequest);
if (adaptor.isEmpty()) {
LOGGER.warn("No metadata could be found for [{}]", issuer);
throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
}
val facade = adaptor.get();
verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade, registeredService);
val binding = determineProfileBinding(authenticationContext);
val acs = SamlIdPUtils.determineEndpointForRequest(Pair.of(authnRequest, authenticationContext.getRight()), facade, binding);
LOGGER.debug("Determined SAML2 endpoint for authentication request as [{}]", StringUtils.defaultIfBlank(acs.getResponseLocation(), acs.getLocation()));
SamlUtils.logSamlObject(configurationContext.getOpenSamlConfigBean(), authnRequest);
return Pair.of(registeredService, facade);
}
use of org.opensaml.saml.saml2.core.AuthnRequest in project cas by apereo.
the class SamlIdPDelegatedClientAuthenticationRequestCustomizer method customize.
@Override
public void customize(final IndirectClient client, final WebContext webContext) {
val authnRequestResult = SamlIdPUtils.retrieveSamlRequest(webContext, sessionStore, openSamlConfigBean, AuthnRequest.class).map(Pair::getLeft).map(AuthnRequest.class::cast);
authnRequestResult.ifPresent(authnRequest -> {
LOGGER.debug("Retrieved the SAML2 authentication request from [{}]", SamlIdPUtils.getIssuerFromSamlObject(authnRequest));
if (authnRequest.isForceAuthn()) {
webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true);
}
if (authnRequest.isPassive()) {
webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true);
}
val requestedAuthnContext = authnRequest.getRequestedAuthnContext();
if (requestedAuthnContext != null && requestedAuthnContext.getAuthnContextClassRefs() != null && !requestedAuthnContext.getAuthnContextClassRefs().isEmpty()) {
val refs = requestedAuthnContext.getAuthnContextClassRefs().stream().map(XSURI::getURI).collect(Collectors.toList());
webContext.setRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_AUTHN_CONTEXT_CLASS_REFS, refs);
webContext.setRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_COMPARISON_TYPE, requestedAuthnContext.getComparison().name());
}
});
}
use of org.opensaml.saml.saml2.core.AuthnRequest in project ddf by codice.
the class IdpHandler method doHttpRedirectBinding.
private void doHttpRedirectBinding(HttpServletRequest request, HttpServletResponse response) throws AuthenticationFailureException {
String redirectUrl;
String idpRequest = null;
String relayState = createRelayState(request);
try {
IDPSSODescriptor idpssoDescriptor = idpMetadata.getDescriptor();
if (idpssoDescriptor == null) {
throw new AuthenticationFailureException(IDP_METADATA_MISSING);
}
StringBuilder queryParams = new StringBuilder("SAMLRequest=").append(encodeAuthnRequest(createAndSignAuthnRequest(false, idpssoDescriptor.getWantAuthnRequestsSigned()), false));
if (relayState != null) {
queryParams.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
}
idpRequest = idpMetadata.getSingleSignOnLocation() + "?" + queryParams;
UriBuilder idpUri = new UriBuilderImpl(new URI(idpRequest));
simpleSign.signUriString(queryParams.toString(), idpUri);
redirectUrl = idpUri.build().toString();
} catch (UnsupportedEncodingException e) {
LOGGER.info("Unable to encode relay state: {}", relayState, e);
throw new AuthenticationFailureException("Unable to create return location");
} catch (SignatureException e) {
String msg = "Unable to sign request";
LOGGER.info(msg, e);
throw new AuthenticationFailureException(msg);
} catch (URISyntaxException e) {
LOGGER.info("Unable to parse IDP request location: {}", idpRequest, e);
throw new AuthenticationFailureException("Unable to determine IDP location.");
}
try {
response.sendRedirect(redirectUrl);
response.flushBuffer();
} catch (IOException e) {
LOGGER.info("Unable to redirect AuthnRequest to {}", redirectUrl, e);
throw new AuthenticationFailureException("Unable to redirect to IdP");
}
}
Aggregations