Authentication with Spring Security + Spring data + MongoDB

前端 未结 2 414
再見小時候
再見小時候 2021-01-30 18:40

I want to use Spring security with MongoDB (using Spring data) and retrieve the users from my own database for spring security. However, I can not do that since my userservice t

2条回答
  •  孤街浪徒
    2021-01-30 19:00

    Create your own authentication provider providing a class that extends the UserDetailservice. Ensure content scanning is enable in your spring context xml file.

        
            
        
    

    @Service
    public class UserModelService implements UserDetailsService
    {
    @Autowired
    private UserModelRepositoryImpl repository;
    
    
    
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        UserModel user = repository.findByUsername(username);
    
         if( user == null )
            throw new UsernameNotFoundException( "Name not found!" );
    
          List authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
    
          return new User(user.getUsername(), user.getSHA1Password(), authorities );
     }
    
    public void saveUserDetails(UserModel userModel)
    {
        repository.save(userModel);
    }
    

    }

    This class will enable spring query mongo for the username and password required for authentication. Next create the user model class.

    public class UserModel
    {
    
    private String id;
    @Indexed(unique=true)
    private String username;
    private String password;
     public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    

    Create the user implementation class that extends the DAO.

    @Service
    public class UserModelService implements UserDetailsService
    {
    @Autowired
    private UserModelRepositoryImpl repository;
    
    
    
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        UserModel user = repository.findByUsername(username);
    
         if( user == null )
            throw new UsernameNotFoundException( "Oops!" );
    
          List authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));
    
          return new User(user.getUsername(), user.getSHA1Password(), authorities );
     }
    

    Finally configure mongo and you're done.

提交回复
热议问题