目前我正在编写自己的自定义@PreAuthorize 注释。 我的情况如下,
KeyCloak JWT权限结构:
"authorization": {
"permissions": [
{
"scopes": [
"GET",
"DELETE",
"POST"
],
"rsid": "6ae9895f-3766-464f-82c4-44f598ec2a93",
"rsname": "record"
}
]
}
应用程序.属性:
auth:
data:
name1: record
name2: device
Property Detail 组件类:
@ConfigurationProperties(prefix = "auth")
@Component
public class SecurityProperty {
private Map<String, String> data;
....
}
控制器:
@RequestMapping (method = RequestMethod.GET,value = "/api/records",
produces = {"application/json"})
@PreAuthorize ("hasAuthority (@securityProperty.getData(). get('name1') "
+ "+ ': GET')")
ResponseEntity<List<SomeDTO>> getRecords() {
...Some Logic
}
@RequestMapping(method = RequestMethod.GET,value = "/api/devices",
produces = { "application/json" })
@PreAuthorize("hasAuthority(@securityProperty.getResources().get('name2') "
+ "+ ':GET')")
ResponseEntity<List<SomeDTO>> getDevices() {
...Some Logic
}
@Retention(RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@PreAuthorize("hasAuthority(@securityProperty.getResources().get(#resource)"
+ ".concat(':GET'))")
public @interface CustomPreAuthorize {
String resource();
}
并在控制器中使用它
@RequestMapping (method = RequestMethod.GET,value = "/api/devices",
produces = {"application/json"})
@CustomPreAuthorize (resource = "name2")
ResponseEntity<List<SomeDTO>> getDevices() {
...Some Logic
}
问题:
Failed to evaluate expression 'hasAuthority(@securityProperty.getResources().get(#resource).concat(':GET'))"
由于还没有对所需修复的回复,现在我们已经通过为注释添加 Aspect 来解决这个问题,并使用 SecurityContextHolder 进行手动权限检查。
@Before("@annotation(CustomPreAuthorize)")
void annotationPointcut() {
//business logic
}
如果我们以更好的方式实现它,我们将积极检查其他解决方案并发布。