@Override public Pair<Boolean, Principal> verify(final RequestContext requestContext, final Credential credential) { val storageInfo = getKeyAndMap(requestContext, credential); val key = storageInfo.getLeft(); val map = storageInfo.getRight(); val authentication = WebUtils.getAuthentication(requestContext); if (authentication == null) { throw new AuthenticationException("No authentication could be found in the current context"); } val principal = authentication.getPrincipal(); if (map.containsKey(key)) { return Pair.of((Boolean) map.get(key), principal); } return Pair.of(Boolean.FALSE, principal); }
/** * Create response entity for authn failure response. * * @param e the e * @param request the http request * @param applicationContext the application context * @return the response entity */ public static ResponseEntity<String> createResponseEntityForAuthnFailure(final AuthenticationException e, final HttpServletRequest request, final ApplicationContext applicationContext) { try { val authnExceptions = e.getHandlerErrors().values() .stream() .map(ex -> mapExceptionToMessage(e, request, applicationContext, ex)) .collect(Collectors.toList()); val errorsMap = new HashMap<String, List<String>>(); errorsMap.put("authentication_exceptions", authnExceptions); LOGGER.warn("[{}] Caused by: [{}]", e.getMessage(), authnExceptions); return new ResponseEntity<>(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(errorsMap), HttpStatus.UNAUTHORIZED); } catch (final JsonProcessingException exception) { LOGGER.error(e.getMessage(), e); return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); } }
if (e.getHandlerErrors().containsKey(UnauthorizedServiceForPrincipalException.class.getSimpleName())) { val url = WebUtils.getUnauthorizedRedirectUrlFromFlowScope(requestContext); if (url != null) { val values = e.getHandlerErrors().values().stream().map(Throwable::getClass).collect(Collectors.toList()); val handlerErrorName = this.errors .stream()
private static String mapExceptionToMessage(final AuthenticationException authnhandlerErrors, final HttpServletRequest request, final ApplicationContext applicationContext, final Throwable ex) { val authnMsg = StringUtils.defaultIfBlank(ex.getMessage(), "Authentication Failure: " + authnhandlerErrors.getMessage()); val authnBundleMsg = getTranslatedMessageForExceptionClass(ex.getClass().getSimpleName(), request, applicationContext); return String.format("%s:%s:%s", ex.getClass().getSimpleName(), authnMsg, authnBundleMsg); }
@Override public Optional<MultifactorAuthenticationProvider> isActivated(final Authentication authentication, final RegisteredService registeredService, final HttpServletRequest httpServletRequest, final Service service) { if (service == null || authentication == null) { LOGGER.debug("No service or authentication is available to determine event for principal"); return Optional.empty(); } val values = resolveEventFromHttpRequest(httpServletRequest); if (values != null && !values.isEmpty()) { LOGGER.debug("Received request as [{}]", values); val providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(ApplicationContextProvider.getApplicationContext()); if (providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context to satisfy [{}]", values); throw new AuthenticationException(); } val providerFound = MultifactorAuthenticationUtils.resolveProvider(providerMap, values.get(0)); if (providerFound.isPresent()) { return providerFound; } LOGGER.warn("No multifactor provider could be found for request parameter [{}]", values); throw new AuthenticationException(); } return Optional.empty(); }
buildSamlResponse(response, request, authenticationContext, casAssertion, binding); } catch (final AuthenticationException e) { LOGGER.error(e.getMessage(), e); val error = e.getHandlerErrors().values() .stream() .map(Throwable::getMessage)
.collect(Collectors.toCollection(LinkedHashSet::new)); if (!p.isSatisfiedBy(authentication, supportingHandlers)) { failures.add(new AuthenticationException("Unable to satisfy authentication policy " + simpleName));
/** * Gets authenticated profile. * * @param request the request * @param response the response * @param requiredPermission the required permission * @return the authenticated profile */ protected CommonProfile getAuthenticatedProfile(final HttpServletRequest request, final HttpServletResponse response, final String requiredPermission) { val manager = Pac4jUtils.getPac4jProfileManager(request, response); val profile = (Optional<CommonProfile>) manager.get(true); if (profile == null || profile.isEmpty()) { throw new AuthenticationException("Unable to locate authenticated profile"); } val p = profile.get(); if (!p.getPermissions().contains(requiredPermission)) { throw new AuthenticationException("Authenticated profile does not carry the UMA protection scope"); } return p; }
@Override public @NonNull Set<AuthenticationHandler> getAuthenticationHandlersForTransaction(final AuthenticationTransaction transaction) { val handlers = getAuthenticationHandlers(); LOGGER.debug("Candidate/Registered authentication handlers for this transaction are [{}]", handlers); val handlerResolvers = getAuthenticationHandlerResolvers(transaction); LOGGER.debug("Authentication handler resolvers for this transaction are [{}]", handlerResolvers); val resolvedHandlers = handlerResolvers.stream() .filter(r -> r.supports(handlers, transaction)) .map(r -> r.resolve(handlers, transaction)) .flatMap(Set::stream) .collect(Collectors.toCollection(LinkedHashSet::new)); if (resolvedHandlers.isEmpty()) { LOGGER.debug("Authentication handler resolvers produced no candidate authentication handler. Using the default handler resolver instead..."); val defaultHandlerResolver = new DefaultAuthenticationHandlerResolver(); if (defaultHandlerResolver.supports(handlers, transaction)) { resolvedHandlers.addAll(defaultHandlerResolver.resolve(handlers, transaction)); } } if (resolvedHandlers.isEmpty()) { throw new AuthenticationException("No authentication handlers could be resolved to support the authentication transaction"); } LOGGER.debug("Resolved and finalized authentication handlers to carry out this authentication transaction are [{}]", handlerResolvers); return resolvedHandlers; }
if (providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context to handle [{}]", globalProviderId); throw new AuthenticationException(); throw new AuthenticationException();
@Override public Optional<MultifactorAuthenticationProvider> isActivated(final Authentication authentication, final RegisteredService registeredService, final HttpServletRequest httpServletRequest, final Service service) { val timedMultifactor = casProperties.getAuthn().getAdaptive().getRequireTimedMultifactor(); if (service == null || authentication == null) { LOGGER.debug("No service or authentication is available to determine event for principal"); return Optional.empty(); } if (timedMultifactor == null || timedMultifactor.isEmpty()) { LOGGER.debug("Adaptive authentication is not configured to require multifactor authentication by time"); return Optional.empty(); } val providerMap = MultifactorAuthenticationUtils.getAvailableMultifactorAuthenticationProviders(ApplicationContextProvider.getApplicationContext()); if (providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context"); throw new AuthenticationException(); } return checkTimedMultifactorProvidersForRequest(registeredService, authentication); }
if (providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context"); throw new AuthenticationException();
/** * Validate event id for matching transition in context event. * * @param eventId the event id * @param context the context * @param attributes the attributes * @return the event */ public static Event validateEventIdForMatchingTransitionInContext(final String eventId, final Optional<RequestContext> context, final Map<String, Object> attributes) { val attributesMap = new LocalAttributeMap<Object>(attributes); val event = new Event(eventId, eventId, attributesMap); return context.map(ctx -> { val def = ctx.getMatchingTransition(event.getId()); if (def == null) { throw new AuthenticationException("Transition definition cannot be found for event " + event.getId()); } return event; }).orElse(event); }
if (providerMap.isEmpty()) { LOGGER.error("No multifactor authentication providers are available in the application context"); throw new AuthenticationException(); LOGGER.error("Adaptive authentication is configured to require [{}] for [{}], yet [{}] is absent in the configuration.", mfaMethod, pattern, mfaMethod); throw new AuthenticationException();
/** * Evaluate produced authentication context. * We apply an implicit security policy of at least one successful authentication. * Then, we apply the configured security policy. * * @param builder the builder * @param transaction the transaction * @param authenticationHandlers the authentication handlers * @throws AuthenticationException the authentication exception */ protected void evaluateFinalAuthentication(final AuthenticationBuilder builder, final AuthenticationTransaction transaction, final Set<AuthenticationHandler> authenticationHandlers) throws AuthenticationException { if (builder.getSuccesses().isEmpty()) { publishEvent(new CasAuthenticationTransactionFailureEvent(this, builder.getFailures(), transaction.getCredentials())); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } val authentication = builder.build(); val failures = evaluateAuthenticationPolicies(authentication, transaction, authenticationHandlers); if (!failures.getKey()) { publishEvent(new CasAuthenticationPolicyFailureEvent(this, builder.getFailures(), transaction, authentication)); failures.getValue().forEach(e -> handleAuthenticationException(e, e.getClass().getSimpleName(), builder)); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses()); } }
throw new AuthenticationException("Resolved credentials for this transaction are empty"); throw new AuthenticationException(builder.getFailures(), builder.getSuccesses());
LOGGER.error("Adaptive authentication is configured to require [{}] for [{}], yet [{}] absent in the configuration.", timed.getProviderId(), service, timed.getProviderId()); throw new AuthenticationException();
@Override protected Event doExecute(final RequestContext requestContext) { val agent = WebUtils.getHttpServletRequestUserAgentFromRequestContext(); val geoLocation = WebUtils.getHttpServletRequestGeoLocationFromRequestContext(); if (geoLocation != null && StringUtils.isNotBlank(agent) && !adaptiveAuthenticationPolicy.apply(requestContext, agent, geoLocation)) { val msg = "Adaptive authentication policy does not allow this request for " + agent + " and " + geoLocation; val map = CollectionUtils.<String, Throwable>wrap(UnauthorizedAuthenticationException.class.getSimpleName(), new UnauthorizedAuthenticationException(msg)); val error = new AuthenticationException(msg, map, new HashMap<>(0)); return new Event(this, CasWebflowConstants.TRANSITION_ID_AUTHENTICATION_FAILURE, new LocalAttributeMap<>(CasWebflowConstants.TRANSITION_ID_ERROR, error)); } val serviceTicketEvent = this.serviceTicketRequestWebflowEventResolver.resolveSingle(requestContext); if (serviceTicketEvent != null) { fireEventHooks(serviceTicketEvent, requestContext); return serviceTicketEvent; } val finalEvent = this.initialAuthenticationAttemptWebflowEventResolver.resolveSingle(requestContext); fireEventHooks(finalEvent, requestContext); return finalEvent; }
if (authentication == null) { throw new InvalidTicketException( new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
@Override @Audit( action = "AUTHENTICATION", actionResolverName = "AUTHENTICATION_RESOLVER", resourceResolverName = "AUTHENTICATION_RESOURCE_RESOLVER") public Authentication authenticate(final AuthenticationTransaction transaction) throws AuthenticationException { val result = invokeAuthenticationPreProcessors(transaction); if (!result) { LOGGER.warn("An authentication pre-processor could not successfully process the authentication transaction"); throw new AuthenticationException("Authentication pre-processor has failed to process transaction"); } AuthenticationCredentialsThreadLocalBinder.bindCurrent(transaction.getCredentials()); val builder = authenticateInternal(transaction); AuthenticationCredentialsThreadLocalBinder.bindCurrent(builder); val authentication = builder.build(); addAuthenticationMethodAttribute(builder, authentication); populateAuthenticationMetadataAttributes(builder, transaction); invokeAuthenticationPostProcessors(builder, transaction); val auth = builder.build(); val principal = auth.getPrincipal(); if (principal instanceof NullPrincipal) { throw new UnresolvedPrincipalException(auth); } LOGGER.info("Authenticated principal [{}] with attributes [{}] via credentials [{}].", principal.getId(), principal.getAttributes(), transaction.getCredentials()); AuthenticationCredentialsThreadLocalBinder.bindCurrent(auth); return auth; }