我正在尝试为当前登录的用户添加一些自定义数据,所以我发现我可以实现自己的 UserDetailsService 并将其插入 Spring,但它从未被调用,我总是将 Principal 作为用户名字符串。
我有我的 UserDetailsService 实现:
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
...
}
}
我对 UserDetails 的实现:
import org.springframework.security.core.userdetails.User;
public class LoggedInUser extends User {
...
}
并尝试以多种方式在配置(SecurityConfiguration)中设置它:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthProvider;
@Autowired
private UserDetailsService userDetailServiceImpl;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
...
}
或者
@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthProvider);
auth.userDetailsService(userDetailServiceImpl).passwordEncoder(passwordService.getPasswordEncoder());
}
或者
@Override
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailServiceImpl();
}
没有任何效果......我尝试了多种方式检索用户信息:
- 在带有@AuthenticationPrincipal 的控制器中,我得到空值
在服务中(我得到无效的演员错误):
身份验证身份验证 = SecurityContextHolder.getContext().getAuthentication(); (LoggedInUser) authentication.getPrincipal()
知道为什么它不起作用吗?我的 impl 类是否在其他地方被默认覆盖?我试图查看日志(logging.level.org.springframework.security=TRACE)但没有运气:/我可以登录,这很好,只是主体数据总是只有用户名字符串而不是我的类。