我创建了HandlerMethodArgumentResolver
的实现,以返回用@CurrentUser
注释的控制器方法的当前登录用户。但是,当调用resolveArgument
的{{1}}方法时,将返回空用户。我已经验证我的自定义HandlerMethodArgumentResolver
实现确实检索了完整的用户对象。
我使用的代码如下。
@CurrUser注释:
UserDetailsService
使用空用户的HandlerMethodArgumentResolver实现:
@Target({ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@AuthenticationPrincipal
public @interface CurrentUser {
}
调用Controller方法:
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Inject
private UserService userService;
@Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(CurrentUser.class) != null
&& parameter.getParameterType().equals(User.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
if (this.supportsParameter(parameter)) {
Principal principal = webRequest.getUserPrincipal();
User user = (User) ((Authentication) principal).getPrincipal(); // This user is empty!!!
return user;
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
检索已填充用户的UserDetailsService的loadUserByUsername(我验证了这是首先调用的):
@RequestMapping(value = "/user", method = RequestMethod.GET)
public HttpEntity<Resource<User>> currentUser(@CurrentUser User self) {
log.debug("CurrentUserController > currentUser GET> " + self);
}
WebMvcConfigurerAdapter配置:
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userService.findByUsername(username);
CustomUserDetails ud = new CustomUserDetails(user);
return ud;
}
答案 0 :(得分:0)
我发现问题是什么 - 问题在于我如何实现`CustomUserDetails':
public static class CustomUserDetails extends User implements UserDetails {
...
}
我正在扩展自定义User类并实现UserDetails
。我不知道为什么,但是Spring不喜欢这个。我之后通过创建和填充新的org.springframework.security.core.userdetails.User
来修复代码,并将其从调用返回到“loadUserByUsername”。