使用授权时可以使用注解进行权限控制,比较常用的有hasRole,hasAnyRole, hasAuthority 。
通过添加角色授权码:
List<SysRole> sysRoleList = sysRoleService.listByUserId(userInfo.getId());
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
sysRoleList.forEach(e -> authorities.add(new SimpleGrantedAuthority(e.getCode())));
@Slf4j
@RestController
public class TestController {
//返回true
@GetMapping(value = "get")
@PreAuthorize("hasRole('ROLE_TEST')")
public Object get(Authentication authentication){
return "权限测试1";
}
//返回false
@GetMapping(value = "get2")
@PreAuthorize("hasRole('role_test')")
public Object get2(Authentication authentication){
return "权限测试2";
}
//返回true
@GetMapping(value = "get3")
@PreAuthorize("hasRole('TEST')")
public Object get3(Authentication authentication){
return "权限测试3";
}
//返回false
@GetMapping(value = "get4")
@PreAuthorize("hasRole('test')")
public Object get4(Authentication authentication){
return "权限测试4";
}
//返回true
@GetMapping(value = "get5")
@PreAuthorize("hasAnyRole('ROLE_TEST')")
public Object get5(Authentication authentication){
return "权限测试5";
}
//返回false
@GetMapping(value = "get6")
@PreAuthorize("hasAnyRole('role_test')")
public Object get6(Authentication authentication){
return "权限测试6";
}
//返回true
@GetMapping(value = "get7")
@PreAuthorize("hasAnyRole('TEST')")
public Object get7(Authentication authentication){
return "权限测试7";
}
//返回false
@GetMapping(value = "get8")
@PreAuthorize("hasAnyRole('test')")
public Object get8(Authentication authentication){
return "权限测试8";
}
//返回true
@GetMapping(value = "get9")
@PreAuthorize("hasAnyAuthority('ROLE_TEST')")
public Object get9(Authentication authentication){
return "权限测试9";
}
//返回false
@GetMapping(value = "get10")
@PreAuthorize("hasAnyAuthority('role_test')")
public Object get10(Authentication authentication){
return "权限测试10";
}
//返回false
@GetMapping(value = "get11")
@PreAuthorize("hasAnyAuthority('TEST')")
public Object get11(Authentication authentication){
return "权限测试11";
}
//返回false
@GetMapping(value = "get12")
@PreAuthorize("hasAnyAuthority('test')")
public Object get12(Authentication authentication){
return "权限测试12";
}
}
hasRole,hasAnyRole:是角色授权,授权代码,在我们返回的UserDetails的Authority需要加ROLE_前缀,所以当授权码为ROLE_TEST时,不论是ROLE_TEST,还是TEST都是返回true。
hasAuthority:是权限授权,自定义的权限,返回的UserDetails的Authority只要与这里匹配就可以。所以当授权码为ROLE_TEST时,只有是ROLE_TEST才会返回true。
注:权限标识判断是区分大小写的。
主要常用表达式说明:
permitAll 永远返回true
denyAll 永远返回false
anonymous 当前用户是anonymous时返回true
rememberMe 当前用户是rememberMe用户时返回true
authenticated 当前用户不是anonymous时返回true
fullAuthenticated 当前用户既不是anonymous也不是rememberMe用户时返回true
hasRole(role) 用户拥有指定的角色权限时返回true
hasAnyRole([role1,role2]) 用户拥有任意一个指定的角色权限时返回true
hasAuthority(authority) 用户拥有指定的权限时返回true
hasAnyAuthority([authority1,authority2]) 用户拥有任意一个指定的权限时返回true
hasIpAddress('127.0.0.1') 请求发送的Ip匹配时返回true