Spring Security---角色授权

之前已经配置好了两个用户java和cpp,不知道如何配置的可以看一下前面的文章。
Spring Security—简介及初体验
Spring Security—表单登陆配置介绍

角色的分配大致是:
jerry:admin角色,拥有所有权限(sys、data)
tom:user角色,拥有查看数据(data)的权限

  • 先写一个简单的controller
@RestController
public class HelloController {
    
    
    @GetMapping("/hello")
    public String hello() {
    
    
        return "hello";
    }

    @GetMapping("/sys/hello")
    public String admin() {
    
    
        return "hello admin";
    }

    @GetMapping("/data/hello")
    public String user() {
    
    
        return "hello user";
    }
}

hello方法作为公共方法,任何人都可以访问
admin方法只有admin用户可以访问
user方法只有user用户可以访问(admin也是user用户)

  • 接下来编写配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication()
                .withUser("jerry")
                .password("javayyds").roles("admin")
                .and()
                .withUser("tom")
                .password("cppyyds").roles("user");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.formLogin()
                .and()
                .authorizeRequests()
                .antMatchers("/sys/**").hasRole("admin")
                .antMatchers("/data/**").hasRole("user")
                .anyRequest().authenticated()
                .and()
                .csrf().disable();
    }

    @Bean
    RoleHierarchy roleHierarchy() {
    
    
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_admin > ROLE_user");
        return hierarchy;
    }
    
}

重写的带有HttpSecurity 参数的configure方法中,antMatchers采用的是蚂蚁风格的路径匹配规则,使用过Spring中注解的AOP编程的人一定对此不陌生。

anyRequest().authenticated()表示其他请求不进行拦截。

需要注意的是,配置的时候要注意顺序,Spring Security和 Shiro一样,在匹配的时候都是按照从上往下的顺序来进行匹配的。

roleHierarchy方法实现了角色的继承,在用户权限中,admin是拥有user的权限,通过角色的继承来继承权限,在setHierarchy的时候要在角色名前加上ROLE_前缀。

这样user用户只拥有hello和data/hello的访问权限,admin就拥有了所有的权限。

猜你喜欢

转载自blog.csdn.net/MAKEJAVAMAN/article/details/120999496