use of org.apereo.cas.authentication.AuthenticationException in project cas by apereo.
the class GrouperMultifactorAuthenticationPolicyEventResolver method resolveInternal.
@Override
public Set<Event> resolveInternal(final RequestContext context) {
final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
final Authentication authentication = WebUtils.getAuthentication(context);
if (StringUtils.isBlank(grouperField)) {
LOGGER.debug("No group field is defined to process for Grouper multifactor trigger");
return null;
}
if (authentication == null) {
LOGGER.debug("No authentication is available to determine event for principal");
return null;
}
final Principal principal = authentication.getPrincipal();
final List<WsGetGroupsResult> results = GrouperFacade.getGroupsForSubjectId(principal.getId());
if (results.isEmpty()) {
LOGGER.debug("No groups could be found for [{}] to resolve events for MFA", principal);
return null;
}
final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
if (providerMap == null || providerMap.isEmpty()) {
LOGGER.error("No multifactor authentication providers are available in the application context");
throw new AuthenticationException();
}
final GrouperGroupField groupField = GrouperGroupField.valueOf(grouperField);
final Set<String> values = results.stream().map(wsGetGroupsResult -> Stream.of(wsGetGroupsResult.getWsGroups())).flatMap(Function.identity()).map(g -> GrouperFacade.getGrouperGroupAttribute(groupField, g)).collect(Collectors.toSet());
final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, values);
if (providerFound.isPresent()) {
if (providerFound.get().isAvailable(service)) {
LOGGER.debug("Attempting to build event based on the authentication provider [{}] and service [{}]", providerFound.get(), service.getName());
final Event event = validateEventIdForMatchingTransitionInContext(providerFound.get().getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, providerFound.get()));
return Collections.singleton(event);
}
LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", providerFound.get());
return null;
}
LOGGER.debug("No multifactor provider could be found based on [{}]'s Grouper groups", principal.getId());
return null;
}
use of org.apereo.cas.authentication.AuthenticationException 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
*/
protected void handleEcpRequest(final HttpServletResponse response, final HttpServletRequest request, final MessageContext soapContext, final Credential credential) {
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 {
final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> serviceRequest = verifySamlAuthenticationRequest(authenticationContext, request);
final Authentication authentication = authenticateEcpRequest(credential, authenticationContext);
buildSamlResponse(response, request, authenticationContext, buildEcpCasAssertion(authentication, serviceRequest.getKey()));
} catch (final AuthenticationException e) {
LOGGER.error(e.getMessage(), e);
final String error = e.getHandlerErrors().values().stream().map(Class::getSimpleName).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()));
}
}
use of org.apereo.cas.authentication.AuthenticationException in project cas by apereo.
the class OidcAuthenticationContextWebflowEventEventResolver method resolveInternal.
@Override
public Set<Event> resolveInternal(final RequestContext context) {
final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
final Authentication authentication = WebUtils.getAuthentication(context);
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
if (service == null || authentication == null) {
LOGGER.debug("No service or authentication is available to determine event for principal");
return null;
}
String acr = request.getParameter(OAuthConstants.ACR_VALUES);
if (StringUtils.isBlank(acr)) {
final URIBuilder builderContext = new URIBuilder(StringUtils.trimToEmpty(context.getFlowExecutionUrl()));
final Optional<URIBuilder.BasicNameValuePair> parameter = builderContext.getQueryParams().stream().filter(p -> p.getName().equals(OAuthConstants.ACR_VALUES)).findFirst();
if (parameter.isPresent()) {
acr = parameter.get().getValue();
}
}
if (StringUtils.isBlank(acr)) {
LOGGER.debug("No ACR provided in the authentication request");
return null;
}
final Set<String> values = org.springframework.util.StringUtils.commaDelimitedListToSet(acr);
if (values.isEmpty()) {
LOGGER.debug("No ACR provided in the authentication request");
return null;
}
final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
if (providerMap == null || providerMap.isEmpty()) {
LOGGER.error("No multifactor authentication providers are available in the application context to handle [{}]", values);
throw new AuthenticationException();
}
final Collection<MultifactorAuthenticationProvider> flattenedProviders = flattenProviders(providerMap.values());
final Optional<MultifactorAuthenticationProvider> provider = flattenedProviders.stream().filter(v -> values.contains(v.getId())).findAny();
if (provider.isPresent()) {
return Collections.singleton(new Event(this, provider.get().getId()));
}
LOGGER.warn("The requested authentication class [{}] cannot be satisfied by any of the MFA providers available", values);
throw new AuthenticationException();
}
use of org.apereo.cas.authentication.AuthenticationException in project cas by apereo.
the class TicketsResource method createTicketGrantingTicket.
/**
* Create new ticket granting ticket.
*
* @param requestBody username and password application/x-www-form-urlencoded values
* @param request raw HttpServletRequest used to call this method
* @return ResponseEntity representing RESTful response
* @throws JsonProcessingException in case of JSON parsing failure
*/
@PostMapping(value = "/v1/tickets", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) throws JsonProcessingException {
try {
final Credential credential = this.credentialFactory.fromRequestBody(requestBody);
final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, credential);
final TicketGrantingTicket tgtId = this.centralAuthenticationService.createTicketGrantingTicket(authenticationResult);
final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(ticketReference);
headers.setContentType(MediaType.TEXT_HTML);
final String tgtUrl = ticketReference.toString();
final String response = new StringBuilder(SUCCESSFUL_TGT_CREATED_INITIAL_LENGTH + tgtUrl.length()).append(DOCTYPE_AND_OPENING_FORM).append(tgtUrl).append(REST_OF_THE_FORM_AND_CLOSING_TAGS).toString();
return new ResponseEntity<>(response, headers, HttpStatus.CREATED);
} catch (final AuthenticationException e) {
final List<String> authnExceptions = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.toList());
final Map<String, List<String>> errorsMap = new HashMap<>();
errorsMap.put("authentication_exceptions", authnExceptions);
LOGGER.error("[{}] Caused by: [{}]", e.getMessage(), authnExceptions, e);
try {
return new ResponseEntity<>(this.jacksonPrettyWriter.writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED);
} catch (final JsonProcessingException exception) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
} catch (final BadRequestException e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
} catch (final Throwable e) {
LOGGER.error(e.getMessage(), e);
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
use of org.apereo.cas.authentication.AuthenticationException in project cas by apereo.
the class AbstractServiceValidateController method handleTicketValidation.
/**
* Handle ticket validation model and view.
*
* @param request the request
* @param service the service
* @param serviceTicketId the service ticket id
* @return the model and view
*/
protected ModelAndView handleTicketValidation(final HttpServletRequest request, final WebApplicationService service, final String serviceTicketId) {
TicketGrantingTicket proxyGrantingTicketId = null;
final Credential serviceCredential = getServiceCredentialsFromRequest(service, request);
if (serviceCredential != null) {
try {
proxyGrantingTicketId = handleProxyGrantingTicketDelivery(serviceTicketId, serviceCredential);
} catch (final AuthenticationException e) {
LOGGER.warn("Failed to authenticate service credential [{}]", serviceCredential);
return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[] { serviceCredential.getId() }, request, service);
} catch (final InvalidTicketException e) {
LOGGER.error("Failed to create proxy granting ticket due to an invalid ticket for [{}]", serviceCredential, e);
return generateErrorView(e.getCode(), new Object[] { serviceTicketId }, request, service);
} catch (final AbstractTicketException e) {
LOGGER.error("Failed to create proxy granting ticket for [{}]", serviceCredential, e);
return generateErrorView(e.getCode(), new Object[] { serviceCredential.getId() }, request, service);
}
}
final Assertion assertion = this.centralAuthenticationService.validateServiceTicket(serviceTicketId, service);
if (!validateAssertion(request, serviceTicketId, assertion)) {
return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_TICKET, new Object[] { serviceTicketId }, request, service);
}
final Pair<Boolean, Optional<MultifactorAuthenticationProvider>> ctxResult = validateAuthenticationContext(assertion, request);
if (!ctxResult.getKey()) {
throw new UnsatisfiedAuthenticationContextTicketValidationException(assertion.getService());
}
String proxyIou = null;
if (serviceCredential != null && this.proxyHandler.canHandle(serviceCredential)) {
proxyIou = handleProxyIouDelivery(serviceCredential, proxyGrantingTicketId);
if (StringUtils.isEmpty(proxyIou)) {
return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_PROXY_CALLBACK, new Object[] { serviceCredential.getId() }, request, service);
}
} else {
LOGGER.debug("No service credentials specified, and/or the proxy handler [{}] cannot handle credentials", this.proxyHandler.getClass().getSimpleName());
}
onSuccessfulValidation(serviceTicketId, assertion);
LOGGER.debug("Successfully validated service ticket [{}] for service [{}]", serviceTicketId, service.getId());
return generateSuccessView(assertion, proxyIou, service, request, ctxResult.getValue(), proxyGrantingTicketId);
}
Aggregations