【问题标题】:Inject EJB in Jersey filter在 Jersey 过滤器中注入 EJB
【发布时间】:2014-01-24 14:21:53
【问题描述】:

我目前正在开发一个以 Jersey JAX-RS 作为后端和 AngularJS 作为前端的应用程序;我需要一种身份验证,因此对于每个请求,我都会发送一个应该由后端验证的令牌。为此,我决定创建一个 Jersey 过滤器来查找该令牌,然后调用我的 AuthenticateService 来检查用户是否可以通过身份验证。 然后由@RolesAllowed 注解管理授权。

这是我的问题:我无法在 Jersey 过滤器中注入 EJB,奇怪的是因为它对资源很有效。但是使用过滤器,服务总是保持 null

知道如何欺骗它吗? 谢谢

过滤代码:

@Provider
@Priority( Priorities.AUTHORIZATION )
public class AuthenticationFilter implements ContainerRequestFilter {

    @EJB( name=AuthenticationService.LOOKUP_NAME)
    private AuthenticationService authService;

    @Override
    public void filter( ContainerRequestContext requestContext ) throws IOException {
        /**
         * Get headers parameters
         */
        String userIdStr = requestContext.getHeaderString( SecurityConsts.HEADER_ID_PARAMETER );
        int userId = 0;

        if( userIdStr != null && !userIdStr.isEmpty() ) {
            userId = Integer.parseInt( userIdStr );
        }

        String securityToken = requestContext.getHeaderString( SecurityConsts.HEADER_TOKEN );

        User user = null;

        /**
         * If a token is present, try to authenticate the user
         */
        if( securityToken != null && !securityToken.isEmpty() ) {
                    // NullPointerException happens here
            user = authService.authenticateWithToken( userId, securityToken );
        }

        /**
         * Set correct security context
         */
        requestContext.setSecurityContext( new ConfiguratorSecurityContext( user ) );
    }

}

【问题讨论】:

    标签: dependency-injection jersey ejb


    【解决方案1】:

    这是一个或多或少知道的问题。

    JAX-RS 2.0 不支持将 EJB 注入 JAX-RS 组件 (提供者、资源)。

    但是有一些选项可以解决这个问题。

    • 您可以尝试切换到 CDI,例如将您的服务变成@ManagedBean 并使用@Inject

    • 您可以尝试通过上下文查找来获取您的服务,如下所示:

      InitialContext context = new InitialContext();
      context.lookup("java:comp/env/ejb/YourBean");
      
    • 您也可以尝试使用 @Stateless 注释您的过滤器,以便它由容器管理。

    您可以找到相关的 JIRA herehere

    另请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 2014-02-20
      • 1970-01-01
      • 2017-11-08
      • 2012-05-11
      • 1970-01-01
      相关资源
      最近更新 更多