需要将“值”传递给我的@CustomPreAuthorize 注释并在@PreAuthorize("hasAuthority(@myservice.check(#value))") 中使用它

问题描述 投票:0回答:1

目前我正在编写自己的自定义@PreAuthorize 注释。 我的情况如下,

  1. 我正在运行我的授权 KeyCloak 服务器,它包含用户详细信息、角色和权限
  2. 验证后,我将权限详细信息存储在 GrantedAuthority 中,如下所示“{rsname}:GET”、“{rsname}:POST”...

KeyCloak JWT权限结构:

"authorization": {
    "permissions": [
      {
        "scopes": [
          "GET",
          "DELETE",
          "POST"
        ],
        "rsid": "6ae9895f-3766-464f-82c4-44f598ec2a93",
        "rsname": "record"
      }
    ]
  }
  1. 在控制器中使用 @PreAuthorize 注释而不是硬编码资源名称和范围时,我们必须通过从 application.property 中获取详细信息来概括它,我们已经实现了如下,

应用程序.属性:

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
}
  1. 到目前为止,一切正常。由于我们正在创建大项目,我们不想编写这个冗长的@PreAuthorize(XXXX) 注释,因此决定创建使用@PreAuthorize 的自定义注释。 我们创建了@CustomPreAuthorize 如下
@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
}

问题:

  1. 当调用 API 时我这样使用时出现以下错误
Failed to evaluate expression 'hasAuthority(@securityProperty.getResources().get(#resource).concat(':GET'))"
  1. 到目前为止,我所理解的是资源和范围在 @PreAuthorize 注释级别中没有得到认可。是否可以读取这样的值,或者是否有其他可用的替代方法?
spring-security authorization spring-annotations spring-el pre-authentication
1个回答
0
投票

由于还没有对所需修复的回复,现在我们已经通过为注释添加 Aspect 来解决这个问题,并使用 SecurityContextHolder 进行手动权限检查。

@Before("@annotation(CustomPreAuthorize)")
void annotationPointcut() {
    //business logic
}

如果我们以更好的方式实现它,我们将积极检查其他解决方案并发布。

© www.soinside.com 2019 - 2024. All rights reserved.