how to use @preauthorize
时间: 2023-09-24 13:11:36 浏览: 87
How to Use Objects
@PreAuthorize is an annotation in Spring Security that is used to secure methods and classes. It allows you to specify access control to methods based on the roles and permissions of the authenticated user.
To use @PreAuthorize, you need to add it to the method or class that you want to secure. For example:
```
@PreAuthorize("hasRole('ROLE_ADMIN')")
public void deleteProduct(Long productId) {
// delete product logic
}
```
In this example, the deleteProduct method can only be accessed by users who have the ROLE_ADMIN role. If a user without this role tries to access the method, Spring Security will throw an AccessDeniedException.
You can also use other expressions in @PreAuthorize to specify more complex access control rules. For example:
```
@PreAuthorize("hasRole('ROLE_ADMIN') or hasPermission(#productId, 'delete')")
public void deleteProduct(Long productId) {
// delete product logic
}
```
In this example, the method can be accessed by users who have the ROLE_ADMIN role or have the delete permission for the specified product.
Note that you'll need to configure Spring Security to use @PreAuthorize. This typically involves adding the @EnableGlobalMethodSecurity annotation to your Spring configuration class.
阅读全文