Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject EJB in Jersey filter

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

Here is my problem : I can't inject an EJB inside a Jersey filter, strangly because it works great with resources.. But with a filter, the service always stays null

Any idea how to trick it ? 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 ) );
    }

}
like image 731
Jérémy Dutheil Avatar asked Jan 24 '14 14:01

Jérémy Dutheil


1 Answers

This is a more or less know problem.

JAX-RS 2.0 does not support injection of EJBs into JAX-RS components (providers, resources).

But there are some options to solve this.

  • You can try switching to CDI, e.g. turning your service into a @ManagedBean and using @Inject.

  • You can try to get your service via context lookup, 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 it gets managed by the container.

You can find related JIRAs here and here.

See also:

  • GlassFish 4 + JAX-RS Filter with @EJB
  • Dependency injection into ResourceFilter not working?
  • How to inject EJB into ResourceFilterFactory (Jersey)
like image 192
unwichtich Avatar answered Dec 22 '22 05:12

unwichtich