我仍然是来自 Grails 背景的 Spring boot 初学者。
已经有很多关于配置的文档。但直到现在我仍然没有任何效果,我想这是因为我仍然不了解 Spring Boot 上配置的整个概念。
我希望我的应用程序使用我自己的数据库表进行身份验证。
我当前的表格是:
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(512) DEFAULT '',
`password` varchar(512) DEFAULT NULL,
`role_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `role` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`role_name` varchar(512) DEFAULT NULL,
PRIMARY KEY (`id`)
);
我尝试使用此类配置我的安全性:
@Configuration
@EnableWebSecurity
@ComponentScan
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(this.dataSource)
.authoritiesByUsernameQuery("select u.username,r.role_name from role r,users u where u.username = ? and u.role_id = r.id")
.usersByUsernameQuery("SELECT username, password FROM users where username = ?")
.passwordEncoder(new BCryptPasswordEncoder());
}
}
但是当我尝试使用正确的凭据访问页面时,我仍然收到 403 错误。
还有什么需要补充的吗?我需要覆盖userDetailsService
我找不到任何明确的文档说明使用“users.username”列作为用户名,“users.password”作为密码或覆盖身份验证查询的方法。
谢谢
最佳答案
UserDetailsService
(JdbcDaoImpl
) 的标准 JDBC 实现需要表来加载密码、帐户状态(启用或禁用)和权限列表(角色)为用户。该架构如下所示:
create table users(
username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(50) not null,
enabled boolean not null
);
create table authorities (
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
constraint fk_authorities_users foreign key(username) references users(username)
);
create unique index ix_auth_username on authorities (username,authority);
所以你应该使用它来加载用户:
usersByUsernameQuery("SELECT username, password, enabled FROM users where username = ?")
这用于加载一个特定用户的所有权限:
select r.role_name from role r,users u where u.username = ? and u.role_id = r.id"
并且基于 .passwordEncoder(new BCryptPasswordEncoder());
您在数据库中保存的密码应使用 BCrypt
进行编码。见春security doc更深入地了解 Spring Security 的工作原理(不是 Spring Boot 的工作原理)。
更新:启用 HTTP 基本安全性:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests().anyRequest().authenticated();
}
要进行身份验证,请添加一个 Authorization
header ,如下所示:
Authorization: Basic <username>:<password>
或者您可以将用户和密码包含在 URL 中:
http://user:passwd@localhost:8080/protected/service
关于java - Spring Boot 使用自定义表进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34721644/