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

我想在MongoDB中使用Spring安全性(使用Spring数据),并从我自己的数据库中检索用户以实现spring安全性。但是,我不能这样做,因为我的用户服务类型似乎不受支持。

这是我的用户服务类:

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);
    }
}

还有我的安全配置类:

@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>.

如何修复它,以便从我自己的数据库中检索用户?


答案 1

服务层

您必须创建一个单独的实现并将其注入到 .serviceorg.springframework.security.core.userdetails.UserDetailsServiceAuthenticationManagerBuilder

@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,它将在春季保留用户经过身份验证的详细信息。您可以包括包裹在其中的实体数据对象,就像我所做的那样。

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); 
    }
}

答案 2

创建您自己的身份验证提供程序,提供扩展用户详细信息服务的类。确保在 spring 上下文 xml 文件中启用内容扫描。

    <authentication-provider user-service-ref="userModelService">
        <password-encoder hash="sha" />
    </authentication-provider>

@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<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));

      return new User(user.getUsername(), user.getSHA1Password(), authorities );
 }

public void saveUserDetails(UserModel userModel)
{
    repository.save(userModel);
}

}

此类将为身份验证所需的用户名和密码启用 spring 查询 mongo。接下来创建用户模型类。

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;
}

创建扩展 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<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority( user.getRole()));

      return new User(user.getUsername(), user.getSHA1Password(), authorities );
 }

最后配置 mongo,你就完成了。