Spring Boot JDBC身份验证不起作用



我创建了一个简单的JDBC身份验证服务。

SecurityConfig:

package com.zsl.qrav.backend.BackendApplication;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery("select username, password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from users where username=?")
;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll();
}
}

我的数据库:

+---------+----------+---------------------------------------------------------------+---------+-----------+
| user_id | username | password                                                      | enabled | role      |
+---------+----------+---------------------------------------------------------------+---------+-----------+
|       1 | qrav     | $2y$10$SYZVfjzt/iwXscoTPp5sf.in3fZ8K9OUNWBWP35T5zh9V.aILxpA2  |       1 | ROLE_USER |
+---------+----------+---------------------------------------------------------------+---------+-----------+

密码仅为"password"散列使用:

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String pass = "password";
String encoded = encoder.encode(pass);
System.out.println(encoded);

问题是,每当我尝试使用凭据qrav:password登录时,它只是说凭据不正确。

MySQL连接没有问题,数据库也没有问题(因为它几乎是YouTube教程中的复制粘贴数据库)。

我不知道出了什么问题,所以我真的很感激你的帮助。

无参数构造函数BCryptPasswordEncoder生成基于Bcrypt版本2a的哈希,但存储在DB中的是版本2y,这就是问题的原因。您需要检查是否有BCryptPasswordEncoder构造函数中指定的版本。

如果使用的是版本<5.2问题在于生成的散列。它应该从$2a$开始。例如,生成了10轮:password =$2a$10$7zE9z3rfDEi7WvF.6Sy2Y.UV2MoVTTkX/AzVXEGpjzG3cZ5EsA1YK

Spring执行以下检查:

private Pattern BCRYPT_PATTERN = Pattern.compile("\A\$2a?\$\d\d\$[./0-9A-Za-z]{53}");

这意味着哈希必须以$2a开头,而不是以$2y开头。

最新更新