I'm using Spring boot 3.0.6, so Spring Security 6.0.3.
Lets supose I do have an endpoint with a @PreAuthorize and a Authority defined
@RestController
@RequestMapping(path = "/perfil")
public class ProfileController {
@GetMapping({ "/all" })
@PreAuthorize("hasAuthority('ROLE_ROL_PROFILE_ADMINISTRATION')")
public ResponseEntity<List<Profile>> findAll() {
List<Profile> list = profileService.findAllProfiles();
return new ResponseEntity<List<Profile>>(list, HttpStatus.OK);
}
}
Also, I do have a @RestControllerAdvice
in a class that implements ErrorController
. There, I'm handling general errors such as HttpRequestMethodNotSupportedException
or AccessDeniedException
.
This is the code:
@RestControllerAdvice
public class BaseExceptionHandler implements ErrorController {
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<HttpResponse> accessDeniedException(AccessDeniedException ex) {
LOGGER.error(ex.getMessage());
String msg = StringUtils.isBlank(ex.getMessage()) ? NOT_ENOUGH_PERMISSIONS : ex.getMessage();
return crearHttpResponse (HttpStatus.FORBIDDEN, msg);
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ResponseEntity<HttpResponse> methodNotSupportedtException(HttpRequestMethodNotSupportedException e) {
HttpMethod methodAllowed = Objects.requireNonNull(e.getSupportedHttpMethods()).iterator().next();
return crearHttpResponse (HttpStatus.METHOD_NOT_ALLOWED, String.format(METHOD_NOT_ALLOWED, methodAllowed));
}
}
As you can see, I can adapt the returning message of the HttpRequestMethodNotSupportedException
using the HttpRequestMethodNotSupportedException.getSupportedHttpMethods()
, so it looks like
That verb is not allowed for the endpoint. Please, make a '%s' request
I'm trying to achieve the same thing with the AccessDeniedException
, informing the user the role
the user is missing. Is there a way to access it?
I have been diving into Spring Security AuthorizationManagerBeforeMethodInterceptor
and the attemptAuthorization
throws new AccessDeniedException("Access Denied");
, so I'm afraid I cannot.
I was tempted to open an issue, but I prefer asking here first.
I also checked Custom Error message with @Preauthorize and @@ControllerAdvice which goes with a pretty similar question, but was related to spring security 3.0.2, so maybe there are better ways of doing what Jan Tomášek did.