@AuthenticationPricipal怎么返回对象
来源:8-1 课程总结
他门说这就是人生
2020-06-28
@GetMapping("/user") public R<SysUser> getCurrentLoginUser(@AuthenticationPrincipal SysUser user) { return R.<SysUser>builder() .success(true) .msg("获取成功!") .data(user) .build(); }
我想这样获取当前用户信息,SysUser实现了UserDetails,R是统一的响应对象而已。这样获取当前用户信息需要哪些条件?
我已经实现并配置了UserDetailsService:
@Component @Primary public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private AccountService accountService; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { SysUser loginUser = accountService.findUserByName(username); return loginUser; } }
@Configuration @EnableWebSecurity //@Order(2) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http .userDetailsService(userDetailsService) .csrf().disable().headers().frameOptions().disable().and() .httpBasic() .and() .authorizeRequests() .anyRequest().authenticated(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
@Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override public void configure(HttpSecurity http) throws Exception { http .userDetailsService(userDetailsService) .authorizeRequests() .antMatchers(HttpMethod.POST, "/account/register").anonymous() .antMatchers("/marriage/avatar/**").permitAll() .anyRequest().authenticated(); } }
为什么@AuthenticationPrincipal注解仍然只能注入String呢?难道还需要哪些条件才能注入UserDetails的实例吗?谢谢老师。
写回答
1回答
-
JoJo
2020-07-09
不用@AuthenticationPrincipal注解,自己写一个解析 SysUser 类型参数的HandlerMethodArgumentResolver 接口的实现即可。参考 https://blog.csdn.net/fgszdgbzdb/article/details/93519752
00
相似问题