【发布时间】:2019-01-27 09:55:49
【问题描述】:
我正在尝试让 JDBC 身份验证与我的小项目一起工作,从外观上看,它应该可以工作,但它没有。所有配置如下。
如果我切换到具有相同用户名/密码的 inMemory 身份验证,它将完美运行。
如果我记录输出,这就是我得到的:
AuthenticationManagerBuilder 配置:
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select user_name as username, password, enabled from gag.users as u where u.user_name=?")
.authoritiesByUsernameQuery("select user_name as username, role from gag.user_roles as u where u.user_name=?");
}
HttpSecurity 配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/post/**").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.and()
.exceptionHandling().accessDeniedPage("/denied")
.and()
.csrf().disable();
// @formatter:on
}
数据库表:
CREATE TABLE gag.USERS(
id SERIAL PRIMARY KEY,
user_name varchar(30) UNIQUE,
password varchar(30),
enabled BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE gag.USER_ROLES(
id SERIAL PRIMARY KEY,
user_name varchar(30) REFERENCES gag.USERS(user_name) NOT NULL,
role varchar(30) NOT NULL,
UNIQUE(user_name, role)
);
INSERT INTO gag.USERS(user_name, password, enabled) VALUES('admin', 'admin', TRUE);
INSERT INTO gag.USER_ROLES(user_name, role) VALUES('admin', 'USER');
任何想法为什么我会为具有正确角色的用户获得 403?
【问题讨论】:
-
hasRole('USER')转换为对ROLE_USER的检查,您的用户没有它有USER。要么将 DB 中的USER值更改为ROLE_USER,要么使用hasPermission代替hasRole。
标签: java spring spring-security