Store the userId with Spring Security Authentication

后端 未结 2 460
庸人自扰
庸人自扰 2021-02-06 17:31

I need to get the userId when the authentication is loading the login, so that I can store it and use it later to gather more information about the by its ID.

Here is my

2条回答
  •  无人及你
    2021-02-06 17:56

    You can have your own AuthenticationProvider to handler your login:

    @Component
    public class AuthenticationProviderBean implements AuthenticationProvider {
    
    @Autowired
    private UserloginDAO userloginDAO;
    
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = null;
        User user = userloginDAO.getUsername(username);
        if(user == null || !userLoginDAO.auth(user.getPassword(), password)){
            throw new BadCredentialsException("Login Unauthenticated");
        }
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,
                                password, Arrays.asList(new MyGrantedAuthority(user)));
        token.setDetails(user);
        return token;
    }
    
    @Override
    public boolean supports(Class authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    
    public class MyGrantedAuthority implements GrantedAuthority{
    
        private static final long serialVersionUID = 5202669007419658413L;
    
        private UserData user;
    
        public MyGrantedAuthority() {
            super();
        }
    
        public MyGrantedAuthority(UserData user){
            this.user = user;
        }
    
        @Override
        public String getAuthority() {
            return user.getRole();
        }
    
    }
    }
    

    Then you can get current user like this:

    User user = (User)SecurityContextHolder.getContext().getAuthentication.getDetails();
    

提交回复
热议问题