配置AuthenticationManagerBuilder以使用用户存储库

时间:2019-01-29 23:40:24

标签: mongodb spring-boot spring-security jwt

我正在尝试使用Spring Boot和JWT保护Rest API。现在,我已经能够拼凑配置的各个部分,以获取使用硬编码的用户名和密码生成的令牌。我希望改用我的User类和存储库。

我已经能够在此处对用户进行硬编码

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
        .withUser("user")
        .password(passwordEncoder().encode("password"))
        .authorities("ROLE_USER");
}

我应该将此指向我的UserDetailsS​​ervice吗?我该怎么办?

@Service
public class UserSecurityService implements UserDetailsService {

  private static final Logger LOG = LoggerFactory.getLogger(UserSecurityService.class);

  @Autowired
  private UserRepository userRepository;

  @Override
  public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);

    if (null == user) {
        LOG.warn("username not found");
        throw new UsernameNotFoundException("Username" + username + "not found");
    }
    return user;
  }
}

1 个答案:

答案 0 :(得分:1)

对于The book object is empty! The Book::isEmpty() should return true --> correct The book object is empty! The Book::isEmpty() should return true --> correct Author: Herbert, Frank Title: Dune ISBN-13: 9780441172719 The Book::isEmpty() should return false --> *incorrect*<= the problem ,您需要UserDetailsService来处理所有身份验证请求。

要这样做:

DaoAuthenticationProvider

上面在内部配置@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(encoder()); } // you shouldn't use plain text @Bean public PasswordEncoder encoder() { return new BCryptPasswordEncoder(); } 。另外,您可以定义要注入的bean:

DaoAuthenticationProvider