我创建了一个简单的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 |
+---------+----------+---------------------------------------------------------------+---------+-----------+
密码是简单的“密码”散列使用:
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String pass = "password";
String encoded = encoder.encode(pass);
System.out.println(encoded);
问题是,每当我尝试使用凭据登录时qrav:password,它只是说,凭据不正确。
mysql连接没有问题,数据库也没有问题(因为它几乎是一个来自youtube教程的复制粘贴数据库)。
我不知道怎么了,所以我真的很感谢你的帮助。
2条答案
按热度按时间72qzrwbm1#
no-args构造函数bcryptpasswordencoder生成一个基于bcryptversion2a的哈希,但数据库中存储的是version2y,这就是问题的原因。您需要检查是否在bcryptpasswordencoder构造函数中指定了版本。
ne5o7dgx2#
如果您使用的是<5.2版本,问题是生成的哈希。应该从
$2a$
. 例如,通过10轮生成以下内容:password=$2a$10$7zE9z3rfDEi7WvF.6Sy2Y.UV2MoVTTkX/AzVXEGpjzG3cZ5EsA1YK
Spring执行以下检查:这意味着散列必须从
$2a
,而你的开始是$2y
.