在Grizzly的哪里挂接身份验证?

Wal*_*inz 5 authentication http grizzly

我正在使用注册了HttpServer两个HttpHandler实例的Grizzly :

  • 下面/api/*是提供产品API的Jersey REST风格的应用程序,以及
  • /*有一个StaticHttpHandler供应静态HTML / JavaScript内容(其中,除其他事项外,在会谈的API/api/

对于身份验证,我目前 使用ContainerRequestFilter实现HTTP Basic Auth 的Jersey来保护API ,该外观与另一个SO问题中提出的内容非常相似。

但是随着需求的变化,现在我想要求对到达服务器的所有请求进行身份验证。因此,我想将身份验证从Jersey升级到Grizzly一级。不幸的是,我完全找不到在Grizzly中可以在哪里连接“请求过滤器”(或任何所谓的过滤器)的方法。有人可以指出我相关的API吗?

rlu*_*bke 4

最简单的解决方案是利用 Grizzly 嵌入式 Servlet 支持。

当然,这意味着您需要做一些工作才能将当前HttpHandler逻辑迁移到Servlets - 但这实际上应该不会太困难,因为HttpHandlerAPI 非常相似。

我将给出一些关于这样做的高层次要点。

HttpServer server = HttpServlet.createSimpleServer(<docroot>, <host>, <port>);
// use "" for <context path> if you want the context path to be /
WebappContext ctx = new WebappContext(<logical name>, <context path>);

// do some Jersey initialization here

// Register the Servlets that were converted from HttpHandlers
ServletRegistration s1 = ctx.addServlet(<servlet name>, <Servlet instance or class name>);
s1.addMapping(<url pattern for s1>);
// Repeat for other Servlets ...

// Now for the authentication Filter ...
FilterRegistration reg = ctx.addFilter(<filter name>, <filter instance or class name>);
// Apply this filter to all requests
reg.addMapping(null, "/*");

// do any other additional initialization work ...

// "Deploy" ctx to the server.
ctx.deploy(server);

// start the server and test ...
Run Code Online (Sandbox Code Playgroud)

注意:Servlet 和 Filter 的动态注册基于 Servlet 3.0 API,因此如果您需要有关如何处理 Servlet 侦听器、初始化参数等的信息,我建议您查看 Servlet 3.0 javadocs。

注意 2:Grizzly Servlet 实现并非 100% 与 Servlet 规范兼容。它不支持标准Servlet注释,也不支持传统Servlet Web应用程序归档部署。

最后,这里有使用嵌入式 Servlet API 的示例