一尘不染

使用Spring Security + Spring数据+ MongoDB进行身份验证

java

我想将Spring安全性与MongoDB结合使用(使用Spring数据),并从我自己的数据库中检索用户以获取Spring安全性。但是,由于我的用户服务类型似乎不受支持,所以我不能这样做。

这是我的UserService类:

public class UserService {
    private ApplicationContext applicationContext;
    private MongoOperations mongoOperations;

    public UserService() {
        applicationContext = new AnnotationConfigApplicationContext(MongoConfig.class);
        mongoOperations = (MongoOperations) applicationContext.getBean("mongoTemplate");
    }

    public User find(String username) {
        return mongoOperations.findOne(Query.query(Criteria.where("username").is(username)), User.class);
    }
}

和我的SecurityConfig类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserService userService;

    @Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userService); //THIS DOES NOT WORK
        builder.inMemoryAuthentication().withUser("username").password("password").roles("USER");
    }

}

我评论的那句话说:

The inferred type UserService is not a valid substitute for the bounded parameter <T extends UserDetailsService>.

如何解决它,以便可以从自己的数据库中检索用户?


阅读 318

收藏
2020-12-03

共1个答案

一尘不染

服务层

您必须创建一个单独的service实现org.springframework.security.core.userdetails.UserDetailsService并将其注入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;
        }
    }
}

模型

UserDetails也应实施。这是POJO,它将在Spring之前保留用户身份验证的详细信息。正如我已经做过的那样,您可以将包装在其中的实体数据对象包括在内。

public class SecUserDetails implements UserDetails {

    private User user;

    public SecUserDetails(User user) {
        this.user = user;
    }
    ......
    ......
    ......
}

安全配置

自动连接我们之前创建的服务,并将其设置在 AuthenticationManagerBuilder

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    SecUserDetailsService userDetailsService ;

    @Autowired
    public void configAuthBuilder(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService); 
    }
}
2020-12-03