Obtaining Active User UserDetails
In Spring controllers, accessing the active (logged in) user's details typically involves retrieving the UserDetails implementation through the SecurityContextHolder. However, Spring offers an alternative approach to simplify this process.
Using @AuthenticationPrincipal
From Spring Security 3.2 onwards, the @AuthenticationPrincipal annotation provides a convenient way to autowire the UserDetails into controllers or methods. By annotating a method parameter with @AuthenticationPrincipal, Spring automatically injects the Principal object, which contains the UserDetails implementation.
Example:
<code class="java">public ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) { ... }</code>
Defining a Custom Argument Resolver (Pre-Spring 3.2)
If you're using an earlier version of Spring Security or need more control, you can implement a custom WebArgumentResolver or HandlerMethodArgumentResolver to retrieve the User object from the Principal.
Example (WebArgumentResolver):
<code class="java">public class CurrentUserWebArgumentResolver implements WebArgumentResolver { @Override public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) { if (methodParameter.isParameterType(User.class) && methodParameter.hasParameterAnnotation(ActiveUser.class)) { Principal principal = webRequest.getUserPrincipal(); return (User) ((Authentication) principal).getPrincipal(); } else { return WebArgumentResolver.UNRESOLVED; } } }</code>
Spring 3.1 (HandlerMethodArgumentResolver):
<code class="java">public class CurrentUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) { if (this.supportsParameter(methodParameter)) { Principal principal = webRequest.getUserPrincipal(); return (User) ((Authentication) principal).getPrincipal(); } else { return WebArgumentResolver.UNRESOLVED; } } }</code>
The above is the detailed content of How to Retrieve Active User Details in Spring Controllers?. For more information, please follow other related articles on the PHP Chinese website!