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