2016-03-01 32 views
3

我正在使用Dropwizard 0.9.2,並且我想創建一個資源,它不需要對GET進行身份驗證,並且需要POST的基本身份驗證。如何使用自定義DropWizard篩選器選擇性地保護資源

我已經試過

@Path("/protectedPing") 
@Produces(MediaType.TEXT_PLAIN) 
public class ProtectedPing { 

@GET 
public String everybody() { 

    return "pingpong"; 
} 

@PermitAll 
@POST 
public String authenticated(){ 
    return "secret pingpong"; 
} 

CachingAuthenticator<BasicCredentials, User> ca = new CachingAuthenticator<>(environment.metrics(), ldapAuthenticator, cbSpec); 
AdminAuthorizer authorizer = new AdminAuthorizer(); 
BasicCredentialAuthFilter<User> bcaf = new BasicCredentialAuthFilter.Builder<User>().setAuthenticator(ca).setRealm("test-oauth").setAuthorizer(authorizer).buildAuthFilter(); 
environment.jersey().register(bcaf); 
environment.jersey().register(RolesAllowedDynamicFeature.class); 
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); 
environment.jersey().register(new ProtectedPing()); 

這似乎導致需要基本身份驗證的所有請求 「/ protectedPing」。

在Dropwizard 0.9.2中,如果我有一個可選的受保護資源,則說明文檔會創建一個自定義過濾器。我假設我需要這樣做,但我不知道從哪裏開始,或者如果那是我真正需要做的。

回答

4

這是一個球衣問題比dropwizard更多的問題。你可以看看這裏:https://jersey.java.net/documentation/latest/filters-and-interceptors.html

基本上你想要的是:

  1. 創建一個註釋,指出要測試的認證(如@AuthenticatePost)

  2. 創建資源並使用@AuthenticatePost註釋正確的方法

  3. 創建您的驗證過濾器(可能類似於您在上面所做的那樣)。

  4. 在動態特徵中,測試註釋是否存在於傳入的資源中。這將適用於後期,假爲獲得。然後直接在資源方法上註冊AuthenticationFilter,而不是在資源上全局註冊。

這將是我將如何解決這個半完成例如:

public class MyDynamicFeature implements DynamicFeature { 

    @Override 
    public void configure(ResourceInfo resourceInfo, FeatureContext context) { 
     if(resourceInfo.getResourceMethod().getAnnotation(AuthenticateMe.class) != null) { 
      context.register(MyAuthFilter.class); 
     } 
    } 

    public class MyAuthFilter implements ContainerRequestFilter { 

     @Override 
     public void filter(ContainerRequestContext requestContext) throws IOException { 
      // do authentication here 
     } 

    } 

    public @interface AuthenticateMe { 

    } 

    @Path("myPath") 
    public class MyResource { 

     @GET 
     public String get() { 
      return "get-method"; 
     } 

     @POST 
     @AuthenticateMe 
     public String post() { 
      return "post-method"; 
     } 
    } 
} 

筆記,所述DynamicFeature檢查該身份驗證註釋存在,與特徵上下文註冊的認證之前。

我希望有幫助,

讓我知道你是否有任何問題。

+0

我最終做了類似的事情,謝謝!我認爲這更像是澤西島的問題,但是從Dropwizard的方向來解決這個問題讓我很難理解澤西島的單詞 – monknomo

+1

我相信Jersey有一個類似的方法,你使用Auth將用戶綁定到資源方法。如果用戶不能創建,它將無法執行該方法。然而,這並不考慮所有預先匹配的過濾器,不管它們是否會運行。如果你有興趣,這裏有一些來自不同問題的信息:http://stackoverflow.com/questions/34304323/issue-with-custom-authorization-in-dropwizard/34334097#34334097 – pandaadb