2015-09-01 46 views
1

在javax servlet過濾器中,有沒有辦法知道請求發往哪個servlet?Servlet過濾器是否知道REST請求的目的地?

我有一些REST資源方法,用JAX-RS(@Path,@GET等)註釋,並由RESTEasy進行掃描。

有一個servlet過濾器檢查每個請求的用戶權限,但我想區分REST資源。 (他們應該要求不同的特權。)

在此階段,已知綁定了REST請求的資源方法?或者只有當請求到達過濾器後面的servlet時才匹配它?

謝謝!

回答

0

編號

唯一可用的信息是請求URL(路徑)。

1

如果您真的想要一些授權相關的業務邏輯,您可以使用ContainerRequestFilter來實現此目的。你可以有一些如下:

public void filter(ContainerRequestContext crc) throws IOException { 
     List<UriTemplate> matchedTemplates = uriInfo.getMatchedTemplates(); 
     String method = crc.getMethod().toLowerCase(); 
     String pathTemplate = ""; 
     String curTemplate = ""; 
     for (UriTemplate template : matchedTemplates) { 
      String templateString = template.getTemplate(); 
      if (template.endsWithSlash()) { 
       curTemplate = templateString.substring(0, templateString.length() - 1); 
      } 
      else { 
       curTemplate = templateString; 
      } 
      pathTemplate = curTemplate + pathTemplate; 
     } 
    // Your authorization logic here once you have the pathTemplate. 
    // pathTemplate (/v1/users/{userId}/cars/{carId}) and the HTTP method 
    // (GET, PUT..) together will determine the choice of servlet 
    // (resource) and the method within to be chosen and invoked. 
} 

您現在可以做基於授權令牌(或任何你正在使用的用戶識別),被調用方法(GET/PUT/POST/DELETE)您的授權檢查和pathTemplate匹配。如果你爲所有資源正確地設計了你的路徑(pathTemplates)(換句話說,如果你有正確的「範圍」你的路徑),一些正則表達式的魔力,你應該沒有問題匹配用戶的授權到一個特定的URL範圍。例如:用戶A使用令牌abc可以在用戶B使用令牌pqr只能訪問/v1/users/pqr/cars/*

不要忘了將它註冊爲球衣資源/過濾器只能訪問/v1/users/abc/*路徑。在dropwizard我們通常做的是:

environment.jersey().register(ApiRequestsFilter.class); 

我希望這有助於

+0

這工作得很好!我使用一個自定義接口註釋了一些「角色」的資源方法。然後,我可以讀取上下文對象中的方法並相應地採取行動(即,如果當前用戶不具備所需角色,則中止)。謝謝! –

0

可以至少3種方式實現這一點:

  1. 通過web.xml中
  2. 的方式通過訪問SecurityContext in the filter
  3. By annotations javax.annotation.security

所有的細節可以在這裏找到:Jersey Security doc

相關問題