Retrieving the Active User's UserDetails
When working with controllers in a Spring application, retrieving the details of the active user can be achieved by accessing the UserDetails implementation.
User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
While this approach is functional, it can be simplified using dependency injection.
Using @AuthenticationPrincipal Annotation
In Spring Security 3.2 and later, the @AuthenticationPrincipal annotation can be utilized. This elegant solution enables direct injection of the UserDetails object into the controller or method.
public ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
Using ArgumentResolvers
Prior to Spring Security 3.2, or if customization is required, argument resolvers can be employed. A WebArgumentResolver, like CurrentUserWebArgumentResolver, can be created to automatically resolve the UserDetails object.
public class CurrentUserWebArgumentResolver implements WebArgumentResolver {
@Override
public Object resolveArgument(...) {
if (...) {
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
This resolver needs to be registered in the application's configuration.
Spring 3.1 : HandlerMethodArgumentResolver
In Spring 3.1 , the HandlerMethodArgumentResolver, like CurrentUserHandlerMethodArgumentResolver, is recommended. It provides similar functionality to the WebArgumentResolver.
public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public Object resolveArgument(...) {
if (...) {
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
This resolver also needs to be registered in the configuration.
By utilizing these methods, you can elegantly obtain the UserDetails of the active user in your controllers, enhancing the maintainability and readability of your Spring application's code.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3