【问题标题】:Configuring AuthenticationManagerBuilder to use User Repository配置 AuthenticationManagerBuilder 以使用用户存储库
【发布时间】:2019-06-23 04:27:43
【问题描述】:

我正在尝试使用 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;
  }
}

【问题讨论】:

    标签: mongodb spring-boot spring-security jwt


    【解决方案1】:

    对于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();
    }
    

    上面内部配置了DaoAuthenticationProvider。或者,您可以定义一个要注入的 bean:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
    
    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(encoder());
        return authProvider;
    }
    

    【讨论】:

    • 我获得了 200 的 auth 认证,但没有生成任何令牌。我得到这个堆栈跟踪'com.backend.Entity.User 不能在 com.backend.Security.JwtAuthenticationFilter.successfulAuthentication(JwtAuthenticationFilter.java:43)' 上转换为 org.springframework.security.core.userdetails.User' 这是这一行var user = ((User) authentication.getPrincipal()); 在我的“JwtAuthenticationFilter.java”类中
    • 该错误告诉您您的User 不是UserDetails,在这种情况下,要解决名称冲突,您需要返回return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getAuthorities())
    • 这是假设您的用户实体(用于数据库)具有用户名、密码和权限...
    • 知道了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多