Search in sources :

Example 11 with AuthenticationException

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;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) WsGetGroupsResult(edu.internet2.middleware.grouperClient.ws.beans.WsGetGroupsResult) MultifactorAuthenticationProviderSelector(org.apereo.cas.services.MultifactorAuthenticationProviderSelector) LoggerFactory(org.slf4j.LoggerFactory) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) TicketRegistrySupport(org.apereo.cas.ticket.registry.TicketRegistrySupport) RequestContext(org.springframework.webflow.execution.RequestContext) Function(java.util.function.Function) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) AuthenticationSystemSupport(org.apereo.cas.authentication.AuthenticationSystemSupport) GrouperFacade(org.apereo.cas.grouper.GrouperFacade) CookieGenerator(org.springframework.web.util.CookieGenerator) ServicesManager(org.apereo.cas.services.ServicesManager) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) Logger(org.slf4j.Logger) StringUtils(edu.internet2.middleware.grouperClientExt.org.apache.commons.lang3.StringUtils) GrouperGroupField(org.apereo.cas.grouper.GrouperGroupField) Audit(org.apereo.inspektr.audit.annotation.Audit) AuthenticationServiceSelectionPlan(org.apereo.cas.authentication.AuthenticationServiceSelectionPlan) Set(java.util.Set) Collectors(java.util.stream.Collectors) RegisteredService(org.apereo.cas.services.RegisteredService) BaseMultifactorAuthenticationProviderEventResolver(org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver) List(java.util.List) Stream(java.util.stream.Stream) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) WebUtils(org.apereo.cas.web.support.WebUtils) Collections(java.util.Collections) Event(org.springframework.webflow.execution.Event) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) WsGetGroupsResult(edu.internet2.middleware.grouperClient.ws.beans.WsGetGroupsResult) Authentication(org.apereo.cas.authentication.Authentication) GrouperGroupField(org.apereo.cas.grouper.GrouperGroupField) Event(org.springframework.webflow.execution.Event) Principal(org.apereo.cas.authentication.principal.Principal)

Example 12 with AuthenticationException

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()));
    }
}
Also used : AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) 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) MessageContext(org.opensaml.messaging.context.MessageContext)

Example 13 with AuthenticationException

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();
}
Also used : MultifactorAuthenticationProviderSelector(org.apereo.cas.services.MultifactorAuthenticationProviderSelector) LoggerFactory(org.slf4j.LoggerFactory) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) TicketRegistrySupport(org.apereo.cas.ticket.registry.TicketRegistrySupport) URIBuilder(org.jasig.cas.client.util.URIBuilder) StringUtils(org.apache.commons.lang3.StringUtils) RequestContext(org.springframework.webflow.execution.RequestContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) AuthenticationSystemSupport(org.apereo.cas.authentication.AuthenticationSystemSupport) CookieGenerator(org.springframework.web.util.CookieGenerator) ServicesManager(org.apereo.cas.services.ServicesManager) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) Logger(org.slf4j.Logger) Collection(java.util.Collection) OAuthConstants(org.apereo.cas.support.oauth.OAuthConstants) AuthenticationServiceSelectionPlan(org.apereo.cas.authentication.AuthenticationServiceSelectionPlan) Set(java.util.Set) RegisteredService(org.apereo.cas.services.RegisteredService) BaseMultifactorAuthenticationProviderEventResolver(org.apereo.cas.web.flow.authentication.BaseMultifactorAuthenticationProviderEventResolver) Optional(java.util.Optional) WebUtils(org.apereo.cas.web.support.WebUtils) Collections(java.util.Collections) Event(org.springframework.webflow.execution.Event) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider) URIBuilder(org.jasig.cas.client.util.URIBuilder) HttpServletRequest(javax.servlet.http.HttpServletRequest) Authentication(org.apereo.cas.authentication.Authentication) Event(org.springframework.webflow.execution.Event)

Example 14 with 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);
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) URI(java.net.URI) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) ResponseEntity(org.springframework.http.ResponseEntity) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) MultiValueMap(org.springframework.util.MultiValueMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 15 with AuthenticationException

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);
}
Also used : Credential(org.apereo.cas.authentication.Credential) HttpBasedServiceCredential(org.apereo.cas.authentication.HttpBasedServiceCredential) Optional(java.util.Optional) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) Assertion(org.apereo.cas.validation.Assertion) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) UnsatisfiedAuthenticationContextTicketValidationException(org.apereo.cas.ticket.UnsatisfiedAuthenticationContextTicketValidationException)

Aggregations

AuthenticationException (org.apereo.cas.authentication.AuthenticationException)21 Event (org.springframework.webflow.execution.Event)10 Authentication (org.apereo.cas.authentication.Authentication)9 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)7 InvalidTicketException (org.apereo.cas.ticket.InvalidTicketException)7 RegisteredService (org.apereo.cas.services.RegisteredService)6 HashMap (java.util.HashMap)5 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)5 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)5 Credential (org.apereo.cas.authentication.Credential)5 Map (java.util.Map)4 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)4 GeneralSecurityException (java.security.GeneralSecurityException)3 Optional (java.util.Optional)3 AccountLockedException (javax.security.auth.login.AccountLockedException)3 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 PreventedException (org.apereo.cas.authentication.PreventedException)3 Service (org.apereo.cas.authentication.principal.Service)3 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)3