Skip to content
Advertisement

Spring Security returns 404 instead of 403 when using @PreAuthorize

After struggling with this for a few days (searching SO for similar questions, doing trial & error), I am tempted to give up…

So the problem is I have a REST service based on Spring Boot using Spring Security and JWT for authentication. Now I want to secure some of the methods to be only called by authorized people using the @PreAuthorize-annotation. This seems to work partly because instead of calling the method Spring returns 404. I would have expected 403.

I have read this SO-question and tried the answers given there, but it did not help. I have moved the @EnableGlobalMethodSecurity(prePostEnabled = true)-Annotation from my SecurityConfiguration to the Application class as suggested elsewhere, still it does not work.

My security configuration looks like this:

JavaScript

}

The controller method looks like this

JavaScript

I am quite sure I am missing something very simple, but I just cannot figure out what.

By the way: if the user requesting the licenses has the ADMIN role everything works as expected, so the problem is not a real 404.

Advertisement

Answer

You need to define the exceptionHandling at security configuration as follows,

JavaScript

You can define AccessDeniedExceptionHandler class as follows,

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement