弹簧安全@AuthenticationPrincipal

新手上路,请多包涵

我一直在尝试让 @AuthenticationPrincipal 与自定义用户类一起正常工作。不幸的是,用户总是空的。这是代码:

控制器

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

}

自定义用户详细信息服务

@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 是最干净的方法,这就是为什么我想让它起作用的原因。任何帮助是极大的赞赏。

原文由 Lukehey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 544
1 个回答

除了使用 @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 会为您注入它。

原文由 Imrank 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题