实现ContainerRequestFilter的类中的JAX-RS注入CDI事件

时间:2018-06-25 19:16:19

标签: java jax-rs cdi jersey-2.0 weld

我正在尝试使用Jersey构建一个JAX-RS Rest API。我正在此线程中投票最多的答案:Best practice for REST token-based authentication with JAX-RS and Jersey

我进入了识别当前用户部分。我正在尝试使用CDI。

这是我的主要应用类别:

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();
    }
}

以及相关的过滤器类:

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
}

当我运行应用程序时,它因以下错误而崩溃:

  

org.glassfish.hk2.api.UnsatisfiedDependencyException:没有   可在以下位置注入的对象   SystemInjecteeImpl(requiredType = Event,parent = AuthenticationFilter,qualifiers = {@ javax.enterprise.inject.Default(),@ appServer.AuthenticatedUser()},position = -1,optional = false,self = false,unqualified = null,997918120 )

我遇到了以下问题:How to use CDI Events in Java Jersey?,但没有相关的答案。 我已经尝试过针对类似问题发布的其他解决方案,但是都没有用。

因此,这里显然是某种注入问题:

@AuthenticatedUser
@Inject
Event<String> userAuthenticatedEvent;

或者我可能没有正确注册过滤器。 有什么建议吗?

0 个答案:

没有答案