2

I'm trying to build a JAX-RS Rest API with Jersey. I'm following the most up-voted answer from this thread: Best practice for REST token-based authentication with JAX-RS and Jersey

I got to the Identifying the current user part. I'm trying to use CDI.

Here is my main app class:

public class Main {
    // Base URI the Grizzly HTTP server will listen on
    public static final String BASE_URI = "http://localhost:8080/myapp/";

    /**
     * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
     * @return Grizzly HTTP server.
     */
    public static HttpServer startServer() {
        // create a resource config that scans for JAX-RS resources and providers
        // in appServer package
        final ResourceConfig rc = new ResourceConfig().packages("appServer");
        rc.register(new CORSFilter());
        rc.register(new AuthenticationFilter());
        // create and start a new instance of grizzly http server
        // exposing the Jersey application at BASE_URI
        return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc, false);
    }

    /**
     * Main method.
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final Weld weld = new Weld();
        weld.initialize();

        final HttpServer server = startServer();
        server.start();
        new SessionUtil().buildSession(args);
        System.out.println(String.format("Jersey app started with WADL available at "
                + "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
        System.in.read();
        server.stop();
        weld.shutdown();
    }
}

And the relevant filter class:

import appServer.AuthenticatedUser;
import appServer.Secured;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import javax.annotation.Priority;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.event.Event;
import javax.enterprise.inject.Default;
import javax.inject.Inject;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

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

    private static final String REALM = "myRealm";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    public AuthenticationFilter() {
        super();
    }


    @Inject
    @AuthenticatedUser
    Event<String> userAuthenticatedEvent;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

            // if successful, fire event with token
            userAuthenticatedEvent.fire(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE,
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
}

When I run the application it crashes with this error:

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at SystemInjecteeImpl(requiredType=Event,parent=AuthenticationFilter,qualifiers={@javax.enterprise.inject.Default(),@appServer.AuthenticatedUser()},position=-1,optional=false,self=false,unqualified=null,997918120)

I have came across this question: How to use CDI Events in Java Jersey? but there was no relevant answer. I have tried other solutions posted for similar problems but none of them worked.

So, it is obviously some sort of injection issue here:

@AuthenticatedUser
@Inject
Event<String> userAuthenticatedEvent;

Or maybe I'm not registering the Filter properly. Any suggestions ?

Rikki Kaka
  • 75
  • 1
  • 3
  • 1
    Doesn't the filter need to be CDI managed? Did you try adding `@ApplicationScoped` to filter and registering it as a class instead of instance? – Paul Samsotha Jun 27 '18 at 04:54
  • 1
    I don't know how to do it correctly in Grizzly, but as you instantiate the filter via `new AuthenticationFilter()` you are definitely bypassing CDI. Thus, look for some kind of grizzly-cdi-module (most servers have that) which enables auto-discovery of filters. If all else fails, let the weld-container init the authentication filter by fetching the WeldContainer from initialize (`WeldContainer container = Weld.initialize()`) and then instantiate by `AuthenticationFilter filter = container.select(AuthenticationFilter.class).get()`. (But please: only as a last resort ;-)) – mtj Jun 27 '18 at 05:35
  • If you annotate the filter with `@Provider`, the grizzly runtime should be able to auto-discover it too. – maress Jun 28 '18 at 11:36

0 Answers0