I am trying to understand the usecase of @AuthenticationPrincipal.
In my controller, I have an method where I use as a parameter
@AuthenticationPrincipal User user
The objective is to get a user from a jwt, so I have created a resolver class which is implementing HandlerMethodArgumentResolver. For the supportsParameters it is my User class, and my resolveArgument get the jwt from the webRequest, decode it and create a User object, this one is returned (And used in my controller method).
I have tried to remove @AuthenticationPrincipal because I am not using the Principal in my class which implements HandlerMethodArgumentResolver, it works perfectly but according to my research it is "very advised" to use this annotation even if it works without.
Does someone know why and how exactly in this case it is/isn't necessary to use @AuthenticationPrincipal, it will help me to have a better comprehension about it ?
Thank you
Why you need to implement HandlerMethodArgumentResolver
to resolve @AuthenticationPrincipal
? Spring security already shipped with an implementation called AuthenticationPrincipalArgumentResolver
for doing such thing and will be enable by default.
As long as you customize the Authentication
to contain your user object and store it to the SecurityContext
after spring security successfully authenticate an user , it should work out of the box.
The only situation you need to implement a HandlerMethodArgumentResolver
is that you are not using spring security but want to specify an user object for the current user as an argument in the controller method. If that is the case , you don't need to annotate @AuthenticationPrincipal
in the controller 's argument as your implementation is nothing do with it.