Insert EJB into filter jersey

I am currently developing an application with JAX-RS Jersey as the backend and AngularJS as the interface; I need authentication, and so with every request I send a token, which should be checked using the backend. To do this, I decided to create a Jersey filter that will look for this token, and then call my AuthenticateService to check if the user can be authenticated. Authorization is then controlled by the @RolesAllowed annotation.

Here is my problem: I cannot inject EJB inside the Jersey filter, it is strange because it works great with resources. But with the filter, the service always remains null

Any idea how to trick him? Thanks

Filter Code:

 @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 ) ); } } 
+7
dependency-injection jersey ejb
source share
1 answer

This is a more or less known problem.

JAX-RS 2.0 does not support EJB injection into JAX-RS components (suppliers, resources).

But there are several solutions to this problem.

  • You can try switching to CDI, for example. turning your service into @ManagedBean and using @Inject .

  • You can try to get your service through contextual search, something like this:

     InitialContext context = new InitialContext(); context.lookup("java:comp/env/ejb/YourBean"); 
  • You can also try to annotate your filter with @Stateless so that it is controlled by the container.

You can find JIRA related here and here .

See also:

  • GlassFish 4 + JAX-RS Filter Using @EJB
  • Does dependency inclusion in ResourceFilter not work?
  • How to introduce EJB in ResourceFilterFactory (Jersey)
+13
source share

All Articles