Authentication with Spring Security + Spring data + MongoDB

前端 未结 2 419
再見小時候
再見小時候 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:02

    Service Layer

    You have to create a separate service implementing org.springframework.security.core.userdetails.UserDetailsService and inject it inside the AuthenticationManagerBuilder.

    @Component
    public class SecUserDetailsService implements UserDetailsService{
    
        @Autowired
        private UserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            /*Here add user data layer fetching from the MongoDB.
              I have used userRepository*/
            User user = userRepository.findByUsername(username);
            if(user == null){
                throw new UsernameNotFoundException(username);
            }else{
                UserDetails details = new SecUserDetails(user);
                return details;
            }
        }
    }
    

    Model

    UserDetails Should be also implemented. This is the POJO which will keep the user authenticated details by the Spring. You may include your Entity data object wrapped inside it, as I have done.

    public class SecUserDetails implements UserDetails {
    
        private User user;
    
        public SecUserDetails(User user) {
            this.user = user;
        }
        ......
        ......
        ......
    }
    

    Security Config

    Autowire the service that we created before and set it inside the AuthenticationManagerBuilder

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        SecUserDetailsService userDetailsService ;
    
        @Autowired
        public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
            builder.userDetailsService(userDetailsService); 
        }
    }
    

提交回复
热议问题