java - 在 Java REST API 中注入(inject) ContainerRequestFilter

标签 java rest glassfish jersey jax-rs

我想我正在处理 Glassfish 4 中的一个错误;但我不确定。基本上我试图将服务注入(inject) ContainerRequestFilter;但我在尝试时遇到异常。我可以在进行休息调用的资源中进行注入(inject),但不能对过滤器使用注入(inject)。 glassfish jira 中有一个已提交的错误:https://java.net/jira/browse/GLASSFISH-20597 .我尝试了其中提到的解决方法,但没有解决我的问题。

这是我得到的异常:

org.glassfish.hk2.api.UnsatisfiedDependencyException: There was no object available for injection at Injectee(requiredType=Authenticator,parent=SecurityInterceptor,qualifiers

这是我正在使用的代码,你知道我在这里遗漏了什么吗?

@Provider
@PreMatching
public class SecurityInterceptor implements ContainerRequestFilter {

@Inject
private Authenticator authenticator; // can't inject this service here, but I can inject this to RequestScoped Resources
private static final Logger LOG = Logger.getLogger(SecurityInterceptor.class.getName());

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    if (!requestContext.getMethod().equals("OPTIONS")) {
        String path = OyumBuFunctions.normalizeString(requestContext.getUriInfo().getPath());
            String authToken = requestContext.getHeaderString(OyumbuRestHeaders.AUTH_TOKEN_HEADER);
            if (!authenticator.isAuthTokenValid(authToken)) {
                requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            }
            else{
                LOG.log(Level.INFO, "authenticated");
            }
    }        
  }
}

最佳答案

我遇到了类似的问题,在寻找解决方案时偶然发现了这篇文章。幸运的是,我找到了解决方案并想将其发布在这里。请注意,这仅适用于 JAX-RS 2.0,因为它使用了 DynamicFeature 类

@Provider
public class AuthenticatorFeature implements DynamicFeature {

    @Inject
    private Autheticator authenticator;

    public void configure(ResourceInfo resourceInfo, FeatureContext context) {
        context.register(new SecurityInterceptor(authenticator);
    }
} 

将身份 validator 绑定(bind)到 ContainerRequestFilter。

public class SecurityInterceptor implements ContainerRequestFilter {
    Authenticator authenticator;  
    public SecurityInterceptor(Authenticator authenticator){
       this.authenticator = authenticator;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        authenticator.doSomething(...);
    }
}

一些希望有用的读物​​

creating resource filters with jersey and jaxrs 2.0

Securing REST Resources with JAX-RS 2.0

关于java - 在 Java REST API 中注入(inject) ContainerRequestFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427710/

相关文章:

node.js - NodeJS 垃圾邮件 GET - REST API

c# - 延迟构建请求

java - 仅在不成对时更换

java - Eclipse 中的信息图标是什么意思?

java - 无法从 Servlet 在本地文件系统上找到文件

ubuntu - GlassFish 6.2.3 看不到 javax.faces.webapp.FacesServlet

java - 无法部署项目

apache - SSL 卸载程序和 Apache 背后的 Glassfish HTTPS 重定向

java - 使用 C 语言通过 FFmpeg 保存部分视频

java - 如何在 java swing 应用程序中包含 sphinx 4