【问题标题】:Spring boot: i keep getting org.springframework.security.authentication.BadCredentialsException: Bad credentials and i dont know whySpring boot:我不断收到 org.springframework.security.authentication.BadCredentialsException:凭据错误,我不知道为什么
【发布时间】:2018-09-09 20:36:53
【问题描述】:

我正在尝试使用 JWT 配置我的 SpringBoot 应用程序,并且每次我尝试使用我的 JWTAuthenticationFilter.class 进行身份验证时,都会收到错误的凭据异常。我觉得整个问题都是由 Bycrpt 造成的,因为通过这个link,,用户抱怨了同样的问题。但是当我实现他的代码时,它对我不起作用。

下面是我的 spring 安全配置器类:

@EnableGlobalMethodSecurity(prePostEnabled = true)

//@配置 @EnableWebSecurity 公共类 JwtSecurityConfiguration 扩展 WebSecurityConfigurerAdapter {

private final CustomerDetailsService customerDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Autowired
public JwtSecurityConfiguration(CustomerDetailsService customerDetailsService) {
    this.customerDetailsService = customerDetailsService;
}

@Autowired
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/resources/**");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/welcome/login").permitAll()
            .antMatchers("**/rest/**").authenticated()
            .and()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    http.addFilterBefore(new JWTAuthenticationFilter(authenticationManager(), 
            (BCryptPasswordEncoder) passwordEncoder()), UsernamePasswordAuthenticationFilter.class);
    http.addFilter(new JWTAuthorizationFilter(authenticationManager(),customerDetailsService));
    http
            .headers()
            .frameOptions().sameOrigin()
            .cacheControl();
}

}

这是 JWTAuthenticationFiler 类:

public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

private AuthenticationManager authenticationManager;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

public JWTAuthenticationFilter(AuthenticationManager authenticationManager, BCryptPasswordEncoder bCryptPasswordEncoder) {
    this.authenticationManager = authenticationManager;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    try {
        User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
    ZonedDateTime expirationTimeUTC = ZonedDateTime.now(ZoneOffset.UTC).plus(EXPIRATION_TIME, ChronoUnit.MILLIS);
    String token = Jwts.builder().setSubject(((User)authResult.getPrincipal()).getUserName())
            .setExpiration(Date.from(expirationTimeUTC.toInstant()))
            .signWith(SignatureAlgorithm.ES256, SECRET)
            .compact();
    response.getWriter().write(token);
    response.addHeader(HEADER, TOKEN_PREFIX + token);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
    super.unsuccessfulAuthentication(request, response, failed);
    response.getWriter().write(failed.getMessage());
}

}

最后这是我的 customerdetailservice 类:

@Component
public class CustomerDetailsService implements UserDetailsService {

@Autowired
DefaultUserDAOService defaultUserDAOService;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = defaultUserDAOService.getByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
    } else {
        return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(),
                AuthorityUtils.createAuthorityList("ROLE_USER"));
    }
}

}

【问题讨论】:

    标签: spring spring-boot spring-security


    【解决方案1】:

    当你添加新用户时,你做了吗:

    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));

    在将其保存到数据库之前? Spring不会为你做这些,你必须自己做。并确保使用相同的算法和盐(如果有)

    检查您的数据库以查看真正保存的密码是什么。

    希望对您有所帮助。

    【讨论】:

    • 是的,我做到了。我完全删除了 Brypt,但我仍然收到错误
    • 也许您可以在调试时启用 Spring Security 日志级别,然后检查日志信息,查看哪个拦截器停止进程并返回错误凭据。确保问题首先发生在您自己的拦截器上。然后我注意到你启用了 EnableGlobalMethodSecurity,先禁用它。您提供的代码不足以调试,但我希望我的建议可以帮助找到原因。
    • Autowired public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } 也将 autowired 更改为 Bean
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2017-05-07
    • 2017-11-23
    • 2019-02-14
    • 2020-03-20
    相关资源
    最近更新 更多