SpringSecurity5.6.2源码分析二十七:GlobalMethodSecurityConfiguration的 作用及使用方式
2024-01-13 08:41:36
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
注解就可以启用注解权限控制了。