Expected Behavior
It would be very useful if the AccessDeniedException contained the AuthorizationDecision which led to the authorization failure.
Current Behavior
No way to get the AuthorizationDecision from the AccessDeniedException. Seems like this info is only available by means of an AuthorizationEvent.
Context
Writing a REST API. Applying method security on RestController methods with @Secured. Using a ControllerAdvice to intercept AccessDeniedExceptions. Using ErrorResponse/ProblemDetail facilities of Spring 6 to produce RFC 9457-compliant error responses, and a proper message bundle feeding the application context message source. I would like to have an error detail message code like this for this kind of error:
problemDetail.org.springframework.security.access.AccessDeniedException=User is missing the required authority; one of: {0}
The list of allowed authorities for the target resource would be available in the AuthorityAuthorizationDecision created by the AuthorityAuthorizationManager when checking for access grant: if I had access to it, I could easily use it to supply the necessary message arguments to get the final problem detail message from the AccessDeniedException in my ControllerAdvice.
The AuthorizationFilter has all of this in its hands, it could just pass the decision to the exception it creates.
Suggestions to any alternative way to achieve this would be welcome.
Comment From: marcusdacoregio
Hi @mauromol, thanks for the report.
We have recently created AuthorizationDeniedException as part of https://github.com/spring-projects/spring-security/issues/14601, and that exception contains the AuthorizationResult.
Since AuthorizationDeniedException extends AccessDeniedException I believe we could change AuthorizationFilter to throw it, the same could be done in org.springframework.security.authorization.AuthorizationManager#verify. I'll bring this discussion to the team and I'll get back to you.
Comment From: mauromol
That would be great, thanks for your feedback!
Comment From: marcusdacoregio
Thanks for the report @mauromol, this is now merged into main and is scheduled for the 6.4.0-M4 release on Sept 16th.