【问题标题】:Spring 4 Security jdbc authenticationSpring 4 安全 jdbc 身份验证
【发布时间】: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


【解决方案1】:

从版本4开始,Spring Security框架自动添加前缀ROLE_。请参阅有关从 Spring Security 3.x 迁移到 4.x 的相关文档:

  • 8. Automatic ROLE_ prefixing:

    Spring Security 4 自动为任何角色添加 ROLE_ 前缀。这些更改是作为SEC-2758 的一部分进行的

    所以你必须将插入更改为:

    INSERT INTO gag.USER_ROLES(user_name, role) VALUES('admin', 'ROLE_USER');
    
  • 8.3. Disable ROLE_ Prefixing

    如果您想省略 ROLE_ 前缀,您可能会发现上面链接的文章很有趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-04
    • 2015-08-08
    • 1970-01-01
    • 2018-10-29
    • 2019-02-21
    • 2012-12-13
    • 1970-01-01
    • 2017-12-06
    相关资源
    最近更新 更多