在一种方法上结合@Secured 和@PreAuthorize 注解

Rus*_*kov 3 java spring spring-mvc spring-security

我的应用程序中有以下服务方法:

    @Override
    @Secured({Authority.ACCESS_FUNDING})
    @PreAuthorize("hasPermission(principal, 'MODIFY')")
    public FundingAllocation newFundingAllocation(FundingAllocationForm fundingAllocationForm) {
      return newFundingAllocation(fundingAllocationForm, null);
    }
Run Code Online (Sandbox Code Playgroud)

但是我注意到@Secured注释被忽略了,只@PreAuthorize执行了检查。

我有以下弹簧安全配置:

  <security:global-method-security secured-annotations="enabled" pre-post-annotations="enabled">
    <security:expression-handler ref="securityExpressionHandler"/>
  </security:global-method-security>
Run Code Online (Sandbox Code Playgroud)

有谁知道是否有可能将一种方法与注释结合起来?

kaq*_*qao 5

根据 Javadoc,DelegatingMethodSecurityMetadataSource它将使用它找到的第一个元数据源。所以不打算将两者混合。https://github.com/spring-projects/spring-security/issues/2116中也解释了基本原理

官方的文档还规定:

您可以在同一个应用程序中启用多种类型的注解,但对于任何接口或类只能使用一种类型,否则行为将无法明确定义。如果发现两个注释适用于特定方法,则仅应用其中一个。

所以不要这样做,并在您的@PreAuthorize:

@PreAuthorized("hasAuthority('ACCESS_FUNDING') and hasPermission(principal, 'MODIFY')")
Run Code Online (Sandbox Code Playgroud)

正如 jmw5598 的回答所暗示的那样。