[英]Spring 4 Security jdbc authentication
我正在尝试使JDBC身份验证与我的小型项目一起工作,从外观上看,它应该可以工作,但不能。 所有配置如下。
如果我切换到具有相同用户名/密码的inMemory auth,则可以正常运行。
这是我在记录输出时得到的:
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的任何想法?
从版本4开始,Spring Security框架会自动添加前缀ROLE_
。 请参阅有关从Spring Security 3.x迁移到4.x的相关文档:
Spring Security 4自动为任何角色添加ROLE_前缀。 所做的更改是SEC-2758的一部分
因此,您必须将插入内容更改为:
INSERT INTO gag.USER_ROLES(user_name, role) VALUES('admin', 'ROLE_USER');
如果您想省略ROLE_
前缀,您可能会发现上面链接的文章很有趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.