返回

SpringSecurity5.6.2源码分析二十七:GlobalMethodSecurityConfiguration的 作用及使用方式

后端

Spring Security中,@Secured@RolesAllowed@PreAuthorize@PostAuthorize这些注解用在了Controller方法的上面,可以用在Spring Boot中。其实,这些注解是由MethodSecurityInterceptor拦截器来解析的,而MethodSecurityInterceptor拦截器是被GlobalMethodSecurityConfiguration这个类给注册的。接下来,我将分析一下GlobalMethodSecurityConfiguration这个类,以及如何使用它。

GlobalMethodSecurityConfiguration的作用

GlobalMethodSecurityConfiguration的主要作用就是注册MethodSecurityInterceptor拦截器,而MethodSecurityInterceptor拦截器则是用来解析@Secured@RolesAllowed@PreAuthorize@PostAuthorize这些注解的。

GlobalMethodSecurityConfiguration的使用方式

要使用GlobalMethodSecurityConfiguration,只需要在Spring Boot项目中添加以下依赖即可:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

添加完依赖之后,就可以在Spring Boot项目中使用@EnableGlobalMethodSecurity注解来启用注解权限控制了。

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

@EnableGlobalMethodSecurity注解有两个参数:

  • prePostEnabled:是否启用@PreAuthorize@PostAuthorize这两个注解。
  • securedEnabled:是否启用@Secured@RolesAllowed这两个注解。

GlobalMethodSecurityConfiguration的示例

以下是一个使用GlobalMethodSecurityConfiguration的示例:

@Controller
public class MyController {

    @GetMapping("/hello")
    @PreAuthorize("hasRole('USER')")
    public String hello() {
        return "hello";
    }
}

在这个示例中,@PreAuthorize注解被用来限制对/hello接口的访问,只有具有USER角色的用户才能访问这个接口。

总结

GlobalMethodSecurityConfiguration是一个非常有用的类,它可以帮助我们轻松地实现注解权限控制。在Spring Boot项目中,只需要添加spring-boot-starter-security依赖,然后在Spring Boot项目中使用@EnableGlobalMethodSecurity注解就可以启用注解权限控制了。