java - 如何修复 Spring Security 中的角色?

我正在尝试在我的项目中使用 Spring Security,代码如下:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // TODO Auto-generated method stub
    //super.configure(auth);
    //auth.inMemoryAuthentication().withUser("admin").password("1111").roles("USER");
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)
            .usersByUsernameQuery("select username, password, 1 from users where username=?")
            .authoritiesByUsernameQuery("select users_username, roles_id  from roles_users where users_username=?")
            .rolePrefix("ROLE_");
}   

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable();      
    http
        .httpBasic();
    http
        .authorizeRequests()
            .anyRequest().authenticated();
    http
        .authorizeRequests()
            .antMatchers("/users/all").hasRole("admin")
            .and()
        .formLogin();
    http
        .exceptionHandling().accessDeniedPage("/403");
}

问题是:

假设我们的数据库中有两个用户(一个具有 user 角色,另一个具有 admin 角色),一个是管理员,另一个是用户,问题是当我作为用户(只有 user 角色)连接时,它可以访问管理资源(这不是预期的行为)。

我认为这个查询中的问题:

"select username, password, 1 from users where username=?" 

根据username为主键?

如果有人知道我该如何解决这个问题?

最佳答案

你的第一个匹配器 anyRequest()始终应用,因为匹配器的顺序很重要,请参阅 HttpSecurity#authorizeRequests :

Note that the matchers are considered in order. Therefore, the following is invalid because the first matcher matches every request and will never get to the second mapping:

http.authorizeRequests().antMatchers("/**").hasRole("USER").antMatchers("/admin/**")
            .hasRole("ADMIN")

您修改和简化的配置:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()      
        .httpBasic()
            .and()
        .authorizeRequests()
            .antMatchers("/users/all").hasRole("admin")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .exceptionHandling().accessDeniedPage("/403");
}

https://stackoverflow.com/questions/48058909/

相关文章:

amazon-web-services - API 网关 - 请求过多异常 (429)

shell - zsh 导出路径在直接输入终端时有效,但在输入/.zshrc 时无效

python-3.x - 系统退出 : 1 Error on using kivy

android - 我如何从 firebase 实时数据库中获取所有数据

javascript - 尝试在 javascript 中捕获未定义的检查

angular - Angular 为 4 的 OrderBy 管道

react-native - 如何在 React Native 中制作局部模糊效果

sql-server - 使用 RDS 检索 Agent SQL 作业的当前执行状态

msbuild - msdeploy 错误 ERROR_USER_UNAUTHORIZED : We

encryption - 如何在 CefPython 中添加 MP4(专有编解码器)支持