首页 > 解决方案 > 方法级别的@PreAuthorize - 如何将类级别变量注入自定义 PreAuthorize 方法参数

问题描述

这是我的代码:

public class MyController {

@Value("${resource.clientId}") // this value is retreiving from vault
private String clientId;

 @PreAuthorize("isClient(#clientId)") //isClient a custom security method
 public String Mymethod(Authentication authentication){

 }
}

如果我使用 clientId 作为 Mymethod 的 arg,那么它工作正常。但与此同时,由于保险库 APPROLE 令牌到期,我面临着“找不到占位符 resource.clientId”之类的问题。

因此决定将方法 arg 更改为上面的类级别变量。但是这个@PreAuthorize [@PreAuthorize("isClient(#clientId)")] 逻辑没有选择clientid。谁能分享一个合适的方法来解决这个问题?我需要在这里使用哪个表达式来解决这个问题?

标签: springspring-security

解决方案


最后,我找到了一个解决方案——我不确定有没有比这更好的解决方案。

public class MyController {

  public static String CLIENT_ID;

  @Value("${resource.clientId}") // this value is retrieving from vault
  public void setClientId(String clientId) {
      CLIENT_ID = clientId;
  }

  @PreAuthorize("isClient({T(com.test.MyController).CLIENT_ID})") //isClient a custom security method
  public String Mymethod(Authentication authentication){

  }

}

使用非静态方法将保险库值注入静态变量,最后将该静态变量传递给 @PreAuthorize 自定义方法。我希望,这对其他人也有帮助..


推荐阅读