Spring Security用户授权

授权,就是用户如果要访问某一个资源,我们检查用户是否具备这样的权限,如果具备就允许访问,如果不具备,则不允许访问。

学习本章之前要先把前面的文章也看下哦。
传送门:
Spring Security初使用
Spring Security自定义表单登录详解
Spring Security 做前后端分离的数据交互

我们准备三个测试接口。如下:

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

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

    @GetMapping("/user/hello")
    public String user() {
        return "user";
    }
}
  1. /hello 是任何人都可以访问的接口
  2. /admin/hello 是具有 admin 身份的人才能访问的接口
  3. /user/hello 是具有 user 身份的人才能访问的接口
  4. 所有 user 能够访问的资源,admin 都能够访问

接下来我们来配置权限的拦截规则,在 Spring Security 的 configure(HttpSecurity http) 方法中,代码如下:

http.authorizeRequests()
        .antMatchers("/admin/**").hasRole("admin")
        .antMatchers("/user/**").hasRole("user")
        .anyRequest().authenticated()
        .and()
        ...
        ...

这里的匹配规则我们采用了 Ant 风格的路径匹配符,Ant 风格的路径匹配符在 Spring 家族中使用非常广泛,它的匹配规则也非常简单:

通配符 含义
** 匹配多层路径
* 匹配一层路径
? 匹配任意单个字符

上面配置的含义是:

  1. 如果请求路径满足 /admin/** 格式,则用户需要具备 admin 角色。
  2. 如果请求路径满足 /user/** 格式,则用户需要具备user 角色。
  3. 剩余的其他格式的请求路径,只需要认证(登录)后就可以访问。

注意代码中配置的三条规则的顺序非常重要,和 Shiro 类似,Spring Security 在匹配的时候也是按照从上往下的顺序来匹配,一旦匹配到了就不继续匹配了。

接下来配置用户,有两种方式:
1.重新configure(AuthenticationManagerBuilder auth)方法实现

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication()
            .withUser("admin")
            .password("admin123").roles("admin")
            .and()
            .withUser("user")
            .password("user123")
            .roles("user");
}

2.重写 WebSecurityConfigurerAdapter 中的 userDetailsService 方法来提供一个 UserDetailService 实例进而配置多个用户

@Bean
protected UserDetailsService userDetailsService() {
    InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
    manager.createUser(User.withUsername("admin").password("admin123").roles("admin").build());
    manager.createUser(User.withUsername("user").password("user123").roles("user").build());
    return manager;
}

选择其中一种方式实现就行。
要实现user 能够访问的资源,admin 都能够访问,还需要进行如下配置:

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

在配置时,需要给角色手动加上 ROLE_ 前缀。上面的配置表示 ROLE_admin 自动具备 ROLE_user 的权限。

接下来就可以启动项目进行测试,登录成功后,分别访问 /hello,/admin/hello 以及 /user/hello 三个接口。
好了到这里授权就结束了。

猜你喜欢

转载自blog.csdn.net/qq_40548741/article/details/107682201