Store the userId with Spring Security Authentication

后端 未结 2 461
庸人自扰
庸人自扰 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();
    
    0 讨论(0)
  • 2021-02-06 17:59

    SecurityContextHolder.getContext().setAuthentication(result); will put the authentication object in SecurityContext which itself maintained in session if the application is a web application.

    Instead of storing the username in session you can retrieve the Authentication object using the following code.

    SecurityContext securityContext = SecurityContextHolder.getContext();
    Object principal;
    String username;
    if(null != securityContext.getAuthentication()){
       principal = securityContext.getAuthentication().getPrincipal();
       username = securityContext.getAuthentication().getName();
    }
    

    Value of username will be the username used in authentication. Value of principal will be the principal object. Many of the authentication providers will create a UserDetails object as the principal.

    Update:

    If you want to store additional information you can extend org.springframework.security.core.userdetails.User and have the additional informations as properties of that class.

    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    
    import java.util.Collection;
    
    public class CustomUser extends User {
    
        private int id;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities,int id) {
            super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
            setId(id);
        }
    }
    

    And in loadUserByUsername return CustomUser instead of User.

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
        empsuite.model.UserData domainUser = userloginDAO.getUsername(username);
    
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
    
        return new CustomUser(
                domainUser.getUsername(),
                domainUser.getPassword(),
                enabled,
                accountNonExpired,
                credentialsNonExpired,
                accountNonLocked,
                getAuthorities(1),
                domainUser.getId());
    
    }
    

    Now securityContext.getAuthentication().getPrincipal() will return CustomUser object. So you can get the ID by ((CustomUser)securityContext.getAuthentication().getPrincipal()).getId()

    SecurityContext securityContext = SecurityContextHolder.getContext();
    CustomUser user;
    if(null != securityContext.getAuthentication()){
       user = (CustomUser) securityContext.getAuthentication().getPrincipal();
    }
    int id = user.getId();
    
    0 讨论(0)
提交回复
热议问题