Spring Security @PreAuthorize 破坏 Jersey @Context UriInfo 注入

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

我正在构建的 Jersey/Spring RESTful Web 应用程序有问题。我想使用 @PreAuthorize 注释来保护我的端点。但是,我需要访问 UriInfo,因为我确实使用查询参数。

一切正常,直到我确保方法安全,然后突然我的 UriInfo 为空。我相当确定这与 @PreAuthorize 如何导致事物被限定范围有关 - 不再是在请求级别。

@Component
@Path("/equipment")
public class Equipment
{
    @Context 
    UriInfo ui;

    @PreAuthorize("hasAnyRole('ROLE_ANALYST', 'ROLE_DEVELOPER')")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public def list() {
        println ui
        return [:]
    }

}

下面的简单类将打印“null”。

如果删除 @PreAuthorize 注释,您将获得预期结果 - org.glassfish.jersey.internal.inject.UriInfoInjectee@23b21e3

根据我在其他问题中看到的内容,让我提前说我的应用程序上下文已经有这一行:

<security:global-method-security pre-post-annotations="enabled"/>

授权部分工作完美。只是 UriInfo 的注入失败了。

我正在使用 Spring 3.1.4 和 Jersey 2.3。提供的代码是 Groovy 中的,但这不是问题。

谢谢您的帮助。

java groovy spring-security jersey jersey-2.0
2个回答
2
投票

所以,我想出了一个解决方案来解决我的问题,并将其留在这里供后代使用。答案并不能满足这一切的“原因”,但它确实让我的应用程序正常工作,而且它并不是一个真正的问题。

我没有在类级别注入 UriInfo,而是在方法级别注入它。我从这里得到了这个想法。他们的解释是,如果方法签名可能被修改,请将其注入那里。我猜 Spring Security 正在这样做,但我不明白为什么这会破坏在类级别注入的东西。

后代的工作代码:

@PreAuthorize("hasAnyRole('ROLE_ANALYST', 'ROLE_DEVELOPER')")
@GET
@Produces(MediaType.APPLICATION_JSON)
public def list(@Context UriInfo ui) {
    ...
}

1
投票

我也遇到了同样的问题,并与之斗争了几个星期。不过,建议的解决方法对我的用途来说并不实用。

我看到建议的另一个解决方法是将 @PreAuthorize 注释向下移动到服务层(或其他一些应用程序层),而不是直接在 REST 资源上使用它。该解决方案对我来说也不实用,但我想我会将其添加为另一种可能性。

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