@EnableGlobalMethodSecurity(prePostEnabled = true)
时间: 2023-07-18 21:11:28 浏览: 47
`@EnableGlobalMethodSecurity(prePostEnabled = true)` 是Spring Security提供的一个注解,用于开启Spring方法级别的安全性。
在Spring Security中,可以通过注解的方式来控制方法的访问权限。使用`@PreAuthorize`或者`@PostAuthorize`注解可以在方法执行前或执行后进行安全验证,从而实现对方法的访问控制。
`@EnableGlobalMethodSecurity(prePostEnabled = true)`注解的作用是开启Spring方法级别的安全性,允许在方法上使用`@PreAuthorize`和`@PostAuthorize`注解。
其中,`@PreAuthorize`和`@PostAuthorize`注解可以使用SpEL表达式来进行安全验证,比如:
```java
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void adminMethod() {
// do something
}
@PostAuthorize("returnObject.owner == authentication.name")
public Object getSomeObject() {
// do something
return someObject;
}
```
这里`@PreAuthorize`注解使用了SpEL表达式`hasRole('ROLE_ADMIN')`,表示只有拥有ROLE_ADMIN角色的用户才能访问该方法。而`@PostAuthorize`注解使用了SpEL表达式`returnObject.owner == authentication.name`,表示只有返回对象的owner属性等于当前用户的用户名时,才能访问该方法。
需要注意的是,使用`@EnableGlobalMethodSecurity(prePostEnabled = true)`注解需要在配置类中添加`@Configuration`注解,例如:
```java
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends GlobalMethodSecurityConfiguration {
// ...
}
```