本文介绍了如何解决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?

推荐答案

您的第一个匹配器始终应用,因为匹配器的顺序很重要,请参阅:

Your first matcher anyRequest() is always applied, because the order of matchers is important, see HttpSecurity#authorizeRequests:

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中的角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:11