gpt4 book ai didi

java - Spring Security @AuthenticationPrincipal

转载 作者:IT老高 更新时间:2023-10-28 13:46:57 24 4
gpt4 key购买 nike

我一直在尝试让 @AuthenticationPrincipal 与自定义 User 类一起正常工作。不幸的是,用户始终为空。代码如下:

Controller

@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());
}

}

CustomUserDetailsS​​ervice

@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 是最干净的方法,这就是我想让它工作的原因。非常感谢任何帮助。

最佳答案

您可以直接在方法参数中指定对经过身份验证的用户的依赖,而不是使用@AuthenticationPrincipal。如下所示

@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(Principal user) {
ModelAndView mav= new ModelAndView("/web/index");
mav.addObject("user", user);
return mav;
}

此 Principal 对象将是通过 Spring Security 进行身份验证的实际对象。当方法被调用时,Spring 会为你注入(inject)这个。

关于java - Spring Security @AuthenticationPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33616386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com