What consideration is this code based on to exclude the need to remember that the token I generate throws an authentication exception in the event of an authorization exception
private void handleAccessDeniedException(HttpServletRequest request, HttpServletResponse response, FilterChain chain, AccessDeniedException exception) throws ServletException, IOException {
Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication();
boolean isAnonymous = this.authenticationTrustResolver.isAnonymous(authentication);
if (!isAnonymous && !this.authenticationTrustResolver.isRememberMe(authentication)) {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Sending %s to access denied handler since access is denied", authentication), exception);
}
this.accessDeniedHandler.handle(request, response, exception);
} else {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.format("Sending %s to authentication entry point since access is denied", authentication), exception);
}
this.sendStartAuthentication(request, response, chain, new InsufficientAuthenticationException(this.messages.getMessage("ExceptionTranslationFilter.insufficientAuthentication", "Full authentication is required to access this resource")));
}
}
Comment From: yyyyyyyysssss
Why is an authentication exception thrown in the method handling insufficient permission exceptions
Comment From: jzheaux
Hi, @yyyyyyyysssss, thanks for the question. The reason is that if authorization fails, and it's because there is no user, then that is more appropriately reported as an authentication failure.
Spring Security behaves this way by default:
- If authentication fails or not present, return a 401
- Otherwise, if authorization fails, return a 403
The ExceptionTranslationFilter mediates the fact that an authorization failure may be due to an underlying lack of authentication. You can read more about this in the reference. This design is what allows you flexibility when you want to add your own authentication strategy.