如何修复 Spring Security 中的角色? [英] How to fix role in Spring Security?

查看:34
本文介绍了如何修复 Spring Security 中的角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use Spring Security in my project, here is the code:

@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 角色)连接时,它可以访问管理资源(这不是预期的行为).

Imagine we have two users (one with the user role and the other one with the admin role) in our database one admin and the second is a user, the problem is when I connect as user (which has only user role) it can access to admin resources (and this is not the expected behavior).

我认为这个查询的问题:

I think the problem in this query:

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

根据username是主键?

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

If anyone has an idea how I can resolve this problem?

推荐答案

你的第一个匹配器 anyRequest() 总是被应用,因为匹配器的顺序很重要,见 HttpSecurity#authorizeRequests:

Your first matcher anyRequest() is always applied, because the order of matchers is important, see 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");
}

这篇关于如何修复 Spring Security 中的角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆