@Preauthorize 中的 Spring Boot 属性

Xtr*_*ica 3 spring spring-security spring-el spring-boot

我正在设置一个 Spring Boot (v1.2.6) web 项目并使用 Spring Security (v3.2.8)。我发现@PreAuthorize注释非常方便,但我不知道是否有办法从注释中的 SpEL 读取 Boot 的属性。我正在尝试这样做:

@PreAuthorize("mysecurity.permit")
Run Code Online (Sandbox Code Playgroud)

使用application.yml 中声明的属性:

mysecurity:
    permit: true
Run Code Online (Sandbox Code Playgroud)

但我得到

Failed to evaluate expression 'mysecurity.permit'
Run Code Online (Sandbox Code Playgroud)

我已经和尝试@mysecurity.permit,并${mysecurity.permit}也具有相同的结果。似乎可以在服务中声明一个方法并以某种@service.isMySecurityPermited()方式访问它,但是我很高兴知道我是否能够直接访问该属性。

dig*_*oel 5

注释中使用的值必须是常量。它们在编译时进行评估,虽然它们可能会保留在运行时使用,但不会重新评估。因此,您可以使用由 SpEL 计算的表达式,或者您可以编写一个在注释值中引用的辅助方法。

如果您查看 OnExpressionCondition 实现,您会注意到它获取传递给注释的值,在您的注释中链接的情况下,该注释将类似于@ConditionalOnExpression("${server.host==localhost} or ${server.port==8080} ") 注释只是获取文本值,它不知道文本代表什么,它只知道它是一个字符串。在 OnExpressionCondition 中处理注释值时,String 值才有意义。他们获取 String 值并将其传递给 BeanExpressionResolver 进行解析。

因此,在你进行预授权解决方案,它基于http://forum.spring.io/forum/spring-projects/security/100708-spel-and-spring-security-3-accessing-bean-reference-in-preauthorize也将它传递给表达式处理器,您应该能够使用 spring 的表达式语言来引用任何 bean 属性。

我目前无法对其进行测试,但是从该线程看来,您可以执行以下操作

@Component
public class MyBean {
  @Value("${mysecurity.permit}")
  private Boolean permit;

  public boolean isPermitted() { return permit; }

  @PreAuthorize( "@myBean.isPermitted()" )
  public blah myMethod() {
    // do stuff
  }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

7923 次

最近记录:

5 年,9 月 前