2013-10-15 48 views
4

我使用的是灰熊HttpServer其中有註冊了兩個HttpHandler實例:在什麼地方掛鉤灰熊認證?

  • /api/*下有一個REST新澤西州 - 風格的應用程序提供產品的API,並
  • /*下有一個StaticHttpHandler這提供靜態HTML/JavaScript內容(其中包括與API對話/api/

對於身份驗證我目前正在保護only使用Jersey ContainerRequestFilter實現HTTP Basic Auth的API,它看起來與another SO question中提供的非常相似。

但隨着需求的變化,現在我想要求驗證所有請求命中服務器。所以我想把驗證級別從澤西移到灰熊。不幸的是,我完全搞不清楚我可以在灰熊中連接一個「請求過濾器」(或者其他所謂的任何東西)。有人可以指點我相關的API來完成這個任務嗎?

回答

3

最簡單的解決方案將利用Grizzly嵌入式Servlet支持。

這當然意味着您需要做一些工作來將您當前的HttpHandler邏輯遷移到Servlet s - 但這確實不應該太難,因爲HttpHandler API非常相似。

我會給出一些關於這樣做的高級要點。

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 ... 

注:servlet和過濾器的動態註冊是基於關閉了Servlet 3.0 API,所以如果你想如何處理與Servlet的監聽器,初始化參數等信息,我建議審查的Servlet 3.0的javadoc。注2:Grizzly Servlet實現與Servlet規範不是100%兼容的。它不支持標準的Servlet註釋或部署傳統的Servlet Web應用程序存檔部署。

最後,有(與灰熊2.3.5測試)使用嵌入的Servlet API的here

0

的 「聯播」 的部分可以使用HttpServerProbe來完成的例子:

srv.getServerConfiguration().getMonitoringConfig().getWebServerConfig() 
.addProbes(new HttpServerProbe.Adapter() { 
    @Override 
    public void onRequestReceiveEvent(HttpServerFilter filter, 
    Connection connection, Request request) { 
    ... 
    } 

    @Override 
    public void onRequestCompleteEvent(HttpServerFilter filter, 
    Connection connection, Response response) { 
    } 
}); 

對於「鏈接「到ContainerRequestFilter你可能想看看我的問題: UnsupportedOperationException getUserPrincipal