【发布时间】:2016-02-10 12:39:36
【问题描述】:
我一直在尝试让 @AuthenticationPrincipal 与自定义 User 类一起正常工作。不幸的是,用户始终为空。代码如下:
控制器
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(@AuthenticationPrincipal User user) {
ModelAndView mav= new ModelAndView("/web/index");
mav.addObject("user", user);
return mav;
}
安全配置
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
}
CustomUserDetailsService
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Spring Data findByXY function
return userRepository.findByUsername(username);
}
用户实体
public class User implements UserDetails{
private String username;
private String password;
private Collection<Authority> authorities;
// Getters and Setters
}
权威实体
public class Authority implements GrantedAuthority{
private User user;
private String role;
// Getters and Setters
@Override
public String getAuthority() {
return this.getRole();
}
}
我已经尝试了各种我在网上找到的解决方案,例如像这样转换我的自定义用户对象:
return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), true, true, true, true, authorities);
获得活跃用户的其他方法都没有问题,但我发现@AuthenticationProvider CustomUserObject 是最干净的方法,这就是我想让它工作的原因。非常感谢任何帮助。
【问题讨论】:
-
嗯.. 你总是可以获取
Principal对象,获取主体名称并通过用户名查找用户。如果春天秒。当然,身份验证正在正确实施。 -
是的,这就是我现在正在做的事情...... Authentication auth = SecurityContextHolder.getContext().getAuthentication();用户主体 = uRep.findByUsername(auth.getName()); .. 但正如我所说,我希望有可用的干净解决方案
-
我面临与您完全相同的问题。 @ AuthenticationPrincipal 总是给我一个默认用户(刚刚使用默认构造函数初始化的 User 类),而 ContextSecurityHolder 和 HttpServletRequest#getUserPrincipal() 给了我预期的(经过身份验证的)用户。顺便说一句,你不应该用@EnableWebSecurity而不是@EnableWebMvcSecurity(在Spring Security 4+中已弃用)来注释你的SecurityConfig吗?
-
感谢您指出这一点,完全错过了:)。如果你弄明白了,请不要犹豫在这里发帖。
-
我在 Spring 提交了 JIRA:jira.spring.io/browse/SEC-3145
标签: java spring spring-security