Spring Security 之方法级的权限管控 @PreAuthorize 使用详解
    		       		warning:
    		            这篇文章距离上次修改已过428天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Security中,@PreAuthorize注解被用来在方法执行前进行权限校验。它可以接受SpEL(Spring Expression Language)表达式来决定是否授权方法的执行。
以下是@PreAuthorize的几种使用方式:
- 使用
hasAuthority()检查用户是否具有特定权限: 
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public void someAdminMethod() {
    // ...
}- 使用
hasAnyAuthority()检查用户是否具有任何给定的权限: 
@PreAuthorize("hasAnyAuthority('ROLE_ADMIN', 'ROLE_USER')")
public void someMethodForAdminOrUser() {
    // ...
}- 使用
principal关键字来引用当前用户: 
@PreAuthorize("principal.username.equals('user123')")
public void someMethodForUser123() {
    // ...
}- 使用
authentication关键字来引用当前的认证信息: 
@PreAuthorize("authentication.principal.enabled == true")
public void someMethodForEnabledUsers() {
    // ...
}- 使用自定义的方法进行权限校验:
 
@PreAuthorize("@myService.checkPermission(#userId, 'read')")
public void someMethodWithCustomPermissionCheck(String userId) {
    // ...
}在这个例子中,myService.checkPermission()是一个自定义的方法,用于检查用户是否具有读权限。
注意:在使用@PreAuthorize时,请确保Spring Security的配置正确,并且已经开启了方法安全性的支持。
评论已关闭