Search in sources :

Example 1 with PrincipalException

use of org.apereo.cas.authentication.PrincipalException in project cas by apereo.

the class RegisteredServiceAccessStrategyUtils method ensurePrincipalAccessIsAllowedForService.

/**
     * Ensure service access is allowed.
     *
     * @param service           the service
     * @param registeredService the registered service
     * @param authentication    the authentication
     * @throws UnauthorizedServiceException the unauthorized service exception
     * @throws PrincipalException           the principal exception
     */
public static void ensurePrincipalAccessIsAllowedForService(final Service service, final RegisteredService registeredService, final Authentication authentication) throws UnauthorizedServiceException, PrincipalException {
    ensureServiceAccessIsAllowed(service, registeredService);
    final Principal principal = authentication.getPrincipal();
    final Map<String, Object> principalAttrs = registeredService.getAttributeReleasePolicy().getAttributes(principal, registeredService);
    if (!registeredService.getAccessStrategy().doPrincipalAttributesAllowServiceAccess(principal.getId(), principalAttrs)) {
        LOGGER.warn("Cannot grant access to service [{}] because it is not authorized for use by [{}].", service.getId(), principal);
        final Map<String, Class<? extends Exception>> handlerErrors = new HashMap<>();
        handlerErrors.put(UnauthorizedServiceForPrincipalException.class.getSimpleName(), UnauthorizedServiceForPrincipalException.class);
        throw new PrincipalException(UnauthorizedServiceForPrincipalException.CODE_UNAUTHZ_SERVICE, handlerErrors, new HashMap<>());
    }
}
Also used : HashMap(java.util.HashMap) PrincipalException(org.apereo.cas.authentication.PrincipalException) Principal(org.apereo.cas.authentication.principal.Principal) PrincipalException(org.apereo.cas.authentication.PrincipalException)

Example 2 with PrincipalException

use of org.apereo.cas.authentication.PrincipalException in project cas by apereo.

the class AbstractServiceValidateController method handleRequestInternal.

@Override
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final WebApplicationService service = this.argumentExtractor.extractService(request);
    final String serviceTicketId = service != null ? service.getArtifactId() : null;
    if (service == null || !StringUtils.hasText(serviceTicketId)) {
        LOGGER.debug("Could not identify service and/or service ticket for service: [{}]", service);
        return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_REQUEST, null, request, service);
    }
    try {
        prepareForTicketValidation(request, service, serviceTicketId);
        return handleTicketValidation(request, service, serviceTicketId);
    } catch (final AbstractTicketValidationException e) {
        final String code = e.getCode();
        return generateErrorView(code, new Object[] { serviceTicketId, e.getService().getId(), service.getId() }, request, service);
    } catch (final AbstractTicketException e) {
        return generateErrorView(e.getCode(), new Object[] { serviceTicketId }, request, service);
    } catch (final UnauthorizedProxyingException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE_PROXY, new Object[] { service.getId() }, request, service);
    } catch (final UnauthorizedServiceException | PrincipalException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE, null, request, service);
    }
}
Also used : WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) AbstractTicketValidationException(org.apereo.cas.ticket.AbstractTicketValidationException) PrincipalException(org.apereo.cas.authentication.PrincipalException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) UnauthorizedProxyingException(org.apereo.cas.services.UnauthorizedProxyingException)

Example 3 with PrincipalException

use of org.apereo.cas.authentication.PrincipalException in project cas by apereo.

the class DefaultCentralAuthenticationService method grantProxyTicket.

@Audit(action = "PROXY_TICKET", actionResolverName = "GRANT_PROXY_TICKET_RESOLVER", resourceResolverName = "GRANT_PROXY_TICKET_RESOURCE_RESOLVER")
@Timed(name = "GRANT_PROXY_TICKET_TIMER")
@Metered(name = "GRANT_PROXY_TICKET_METER")
@Counted(name = "GRANT_PROXY_TICKET_COUNTER", monotonic = true)
@Override
public ProxyTicket grantProxyTicket(final String proxyGrantingTicket, final Service service) throws AbstractTicketException {
    final ProxyGrantingTicket proxyGrantingTicketObject = getTicket(proxyGrantingTicket, ProxyGrantingTicket.class);
    final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
    try {
        final AuditableContext audit = AuditableContext.builder().service(service).ticketGrantingTicket(proxyGrantingTicketObject).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.FALSE).build();
        final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
        accessResult.throwExceptionIfNeeded();
        RegisteredServiceAccessStrategyUtils.ensureServiceSsoAccessIsAllowed(registeredService, service, proxyGrantingTicketObject);
    } catch (final PrincipalException e) {
        throw new UnauthorizedSsoServiceException();
    }
    evaluateProxiedServiceIfNeeded(service, proxyGrantingTicketObject, registeredService);
    // Perform security policy check by getting the authentication that satisfies the configured policy
    // This throws if no suitable policy is found
    getAuthenticationSatisfiedByPolicy(proxyGrantingTicketObject.getRoot().getAuthentication(), new ServiceContext(service, registeredService));
    final Authentication authentication = proxyGrantingTicketObject.getRoot().getAuthentication();
    AuthenticationCredentialsThreadLocalBinder.bindCurrent(authentication);
    final Principal principal = authentication.getPrincipal();
    final ProxyTicketFactory factory = (ProxyTicketFactory) this.ticketFactory.get(ProxyTicket.class);
    final ProxyTicket proxyTicket = factory.create(proxyGrantingTicketObject, service, ProxyTicket.class);
    this.ticketRegistry.updateTicket(proxyGrantingTicketObject);
    this.ticketRegistry.addTicket(proxyTicket);
    LOGGER.info("Granted ticket [{}] for service [{}] for user [{}]", proxyTicket.getId(), service.getId(), principal.getId());
    doPublishEvent(new CasProxyTicketGrantedEvent(this, proxyGrantingTicketObject, proxyTicket));
    return proxyTicket;
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) RegisteredService(org.apereo.cas.services.RegisteredService) ProxyTicketFactory(org.apereo.cas.ticket.proxy.ProxyTicketFactory) UnauthorizedSsoServiceException(org.apereo.cas.services.UnauthorizedSsoServiceException) PrincipalException(org.apereo.cas.authentication.PrincipalException) MixedPrincipalException(org.apereo.cas.authentication.exceptions.MixedPrincipalException) ServiceContext(org.apereo.cas.services.ServiceContext) Authentication(org.apereo.cas.authentication.Authentication) ProxyGrantingTicket(org.apereo.cas.ticket.proxy.ProxyGrantingTicket) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) Principal(org.apereo.cas.authentication.principal.Principal) ProxyTicket(org.apereo.cas.ticket.proxy.ProxyTicket) CasProxyTicketGrantedEvent(org.apereo.cas.support.events.ticket.CasProxyTicketGrantedEvent) Audit(org.apereo.inspektr.audit.annotation.Audit) Counted(com.codahale.metrics.annotation.Counted) Metered(com.codahale.metrics.annotation.Metered) Timed(com.codahale.metrics.annotation.Timed)

Example 4 with PrincipalException

use of org.apereo.cas.authentication.PrincipalException in project cas by apereo.

the class OAuth20AuthorizeEndpointController method redirectToCallbackRedirectUrl.

/**
 * Redirect to callback redirect url model and view.
 *
 * @param manager           the manager
 * @param registeredService the registered service
 * @param context           the context
 * @param clientId          the client id
 * @return the model and view
 */
protected ModelAndView redirectToCallbackRedirectUrl(final ProfileManager manager, final OAuthRegisteredService registeredService, final J2EContext context, final String clientId) {
    final Optional<UserProfile> profile = manager.get(true);
    if (profile == null || !profile.isPresent()) {
        LOGGER.error("Unexpected null profile from profile manager. Request is not fully authenticated.");
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final Service service = this.authenticationBuilder.buildService(registeredService, context, false);
    LOGGER.debug("Created service [{}] based on registered service [{}]", service, registeredService);
    final Authentication authentication = this.authenticationBuilder.build(profile.get(), registeredService, context, service);
    LOGGER.debug("Created OAuth authentication [{}] for service [{}]", service, authentication);
    try {
        final AuditableContext audit = AuditableContext.builder().service(service).authentication(authentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
        final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
        accessResult.throwExceptionIfNeeded();
    } catch (final UnauthorizedServiceException | PrincipalException e) {
        LOGGER.error(e.getMessage(), e);
        return OAuth20Utils.produceUnauthorizedErrorView();
    }
    final View view = buildAuthorizationForRequest(registeredService, context, clientId, service, authentication);
    if (view != null) {
        return OAuth20Utils.redirectTo(view);
    }
    LOGGER.debug("No explicit view was defined as part of the authorization response");
    return null;
}
Also used : AuditableContext(org.apereo.cas.audit.AuditableContext) UserProfile(org.pac4j.core.profile.UserProfile) Authentication(org.apereo.cas.authentication.Authentication) PrincipalException(org.apereo.cas.authentication.PrincipalException) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult) ModelAndView(org.springframework.web.servlet.ModelAndView) View(org.springframework.web.servlet.View)

Example 5 with PrincipalException

use of org.apereo.cas.authentication.PrincipalException in project cas by apereo.

the class ChainingPrincipalResolver method resolve.

/**
 * {@inheritDoc}
 * Resolves a credential by delegating to each of the configured resolvers in sequence. Note that the
 * final principal is taken from the first resolved principal in the chain, yet attributes are merged.
 *
 * @param credential Authenticated credential.
 * @param principal  Authenticated principal, if any.
 * @return The principal from the last configured resolver in the chain.
 */
@Override
public Principal resolve(final Credential credential, final Principal principal, final AuthenticationHandler handler) {
    final List<Principal> principals = new ArrayList<>();
    chain.stream().filter(resolver -> resolver.supports(credential)).forEach(resolver -> {
        LOGGER.debug("Invoking principal resolver [{}]", resolver);
        final Principal p = resolver.resolve(credential, principal, handler);
        if (p != null) {
            principals.add(p);
        }
    });
    if (principals.isEmpty()) {
        LOGGER.warn("None of the principal resolvers in the chain were able to produce a principal");
        return NullPrincipal.getInstance();
    }
    final Map<String, Object> attributes = new HashMap<>();
    principals.forEach(p -> {
        if (p != null) {
            LOGGER.debug("Resolved principal [{}]", p);
            if (p.getAttributes() != null && !p.getAttributes().isEmpty()) {
                LOGGER.debug("Adding attributes [{}] for the final principal", p.getAttributes());
                attributes.putAll(p.getAttributes());
            }
        }
    });
    final long count = principals.stream().map(p -> p.getId().trim().toLowerCase()).distinct().collect(Collectors.toSet()).size();
    if (count > 1) {
        throw new PrincipalException("Resolved principals by the chain are not unique because principal resolvers have produced CAS principals " + "with different identifiers which typically is the result of a configuration issue.", new HashMap<>(0), new HashMap<>(0));
    }
    final String principalId = principal != null ? principal.getId() : principals.get(0).getId();
    final Principal finalPrincipal = this.principalFactory.createPrincipal(principalId, attributes);
    LOGGER.debug("Final principal constructed by the chain of resolvers is [{}]", finalPrincipal);
    return finalPrincipal;
}
Also used : PrincipalException(org.apereo.cas.authentication.PrincipalException) Setter(lombok.Setter) NullPrincipal(org.apereo.cas.authentication.principal.NullPrincipal) PrincipalResolver(org.apereo.cas.authentication.principal.PrincipalResolver) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) IPersonAttributeDao(org.apereo.services.persondir.IPersonAttributeDao) ArrayList(java.util.ArrayList) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) Map(java.util.Map) ToString(lombok.ToString) Principal(org.apereo.cas.authentication.principal.Principal) Credential(org.apereo.cas.authentication.Credential) DefaultPrincipalFactory(org.apereo.cas.authentication.principal.DefaultPrincipalFactory) MergingPersonAttributeDaoImpl(org.apereo.services.persondir.support.MergingPersonAttributeDaoImpl) HashMap(java.util.HashMap) PrincipalException(org.apereo.cas.authentication.PrincipalException) ArrayList(java.util.ArrayList) ToString(lombok.ToString) NullPrincipal(org.apereo.cas.authentication.principal.NullPrincipal) Principal(org.apereo.cas.authentication.principal.Principal)

Aggregations

PrincipalException (org.apereo.cas.authentication.PrincipalException)5 Principal (org.apereo.cas.authentication.principal.Principal)3 HashMap (java.util.HashMap)2 AuditableContext (org.apereo.cas.audit.AuditableContext)2 AuditableExecutionResult (org.apereo.cas.audit.AuditableExecutionResult)2 Authentication (org.apereo.cas.authentication.Authentication)2 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)2 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)2 Counted (com.codahale.metrics.annotation.Counted)1 Metered (com.codahale.metrics.annotation.Metered)1 Timed (com.codahale.metrics.annotation.Timed)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Map (java.util.Map)1 Collectors (java.util.stream.Collectors)1 Setter (lombok.Setter)1 ToString (lombok.ToString)1 Slf4j (lombok.extern.slf4j.Slf4j)1 AuthenticationHandler (org.apereo.cas.authentication.AuthenticationHandler)1 Credential (org.apereo.cas.authentication.Credential)1