【问题标题】:@PreAuthorize invoked on one method but not another@PreAuthorize 在一种方法上调用,但不是在另一种方法上调用
【发布时间】:2012-01-30 06:48:12
【问题描述】:

在我的 spring 配置文件中,我有 <global-method-security pre-post-annotations="enabled"/>

在我的春季@Controller 中,我有一个@RequestMapping,上面有一个@PreAuthorize,如下所示:

@PreAuthorize("true == false")
@RequestMapping(value="/image", method=RequestMethod.GET )
@ResponseBody
public ResponseEntity<byte[]> getImage(
        @RequestParam(value="imageSet", required=false) Long imageSetKey
        , @RequestParam(required=false, defaultValue="70") Integer size
        , @RequestParam(required=false) Unit unit
        , @RequestHeader( value="if-none-match", required=false ) String etag 
)
{
    // use the latest and greatest for the unit if they specify the unit, otherwise use the imageSetKey they pass in.
    if ( unit != null )
    {
        return getUnitImage( unit, size, etag );
    }
    // more code to do other stuff
}

现在这个@PreAuthorize 被评估并正常工作。如果我在 getUnitImage 方法上放置了 PreAuthorize,那么它不会被评估,我可以很好地进入该方法。这是不评估 @PreAuthorize 的方法。

@PreAuthorize("true == false")
public ResponseEntity<byte[]> getUnitImage( Unit unit, int size, String etag )
{
    // do stuff, I get into breakpoints here.
}

思考为什么 PreAuthorize 会在一个带有 RequestMapping 的方法上被调用,而不是在同一个类中的其他方法上?

Spring 3.0.5、Spring 安全 3.0.3

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    这是由 Spring AOP 和 CGLIB 的工作方式引起的。具体来说,会创建一个代理类来扩展您的实际类,这就是提供 @PreAuthorize 行为的实现的原因。当您从同一个类调用方法时,它不会通过代理类,因此不会执行所需的行为。

    解决此问题的一种方法是改用 AspectJ,方法是将 mode="aspectj" 添加到 Spring 配置中的 global-method-security 元素。

    @Transactional 也会发生这种情况,另外一个专门针对 @Transactional 的问题提供了有关此问题的更多详细信息:

    Spring @Transaction method call by the method within the same class, does not work?

    【讨论】:

      【解决方案2】:

      getUnitImage 方法是如何被调用的?

      确保您调用它的方式允许代理(即为注释创建的代理)拦截调用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-10
        • 2011-12-13
        • 2014-12-13
        • 2011-07-05
        • 2020-06-18
        • 2012-03-22
        • 1970-01-01
        • 2014-05-08
        相关资源
        最近更新 更多