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

查看:610
本文介绍了如何解决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");
}

以下是问题所在:

想象一下,我们有两个用户(一个用用户角色,另一个用 admin 角色)在我们的数据库中有一个管理员,第二个是用户,问题是当我以用户身份连接时(只有用户角色),它可以访问管理资源(这是不是预期的行为。)

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=?" 

根据用户名是主键吗?

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

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天全站免登陆