2016-09-14 43 views
0

我正在使用Jersey + Jetty + Dropwizard + Hibernate創建Web服務。在Jersey web服務中設置角色

比方說,我有這樣一個網絡資源:

@Path("/") 
@PermitAll 
public class Resource { 
    @RolesAllowed("user") 
    @GET 
    public String get() { return "GET"; } 


@RolesAllowed("admin") 
@POST 
public String post(String content) { return content; } 

@Path("sub") 
public SubResource getSubResource() { 
    return new SubResource(); 
} 
} 

我知道你可以用HttpServletRequest.isUserInRole檢查用戶的角色。

的問題是,我該如何分配開始與角色?澤西如何知道要爲isUserInRole方法返回什麼,或知道如何過濾人們根據他們的角色沒有獲得特定資源?

我沒有web.xmlwebdefault.xml,所以定義應該在其他地方完成。

+0

你看的文檔爲[Dropwizard驗證(http://www.dropwizard.io/1.0.0/docs/manual/auth.html)?它支持Basic和OAuth。還有第三方[JWT的lib](https://github.com/ToastShaman/dropwizard-auth-jwt)。所有這些角色的東西都由框架處理。除非你有這些解決方案並且你沒有爲你工作,並且你想自己創建 –

回答

0

您必須提供一個支持@RolesAllowed(「admin」)批註的提供者類,然後您必須在應用程序中註冊提供者類。正常情況下,它是在web.xml中完成的,但是因爲您沒有使用它,你必須自己提供。相關示例可以發現here

+0

這個例子包括在web.xml文件中進行設置,我說我沒有 –

+0

那麼你是如何加載你的澤西servlet的。你必須使用一些配置文件或註釋(@webservlet)。你必須在那裏加載它。 –

+0

我得到了config.yml文件和資源等的所有配置與dropwizard的配置類 –

0

Jersey使用自己的機制來檢查角色(請參閱SecurityContext接口),但是如果未明確設置,它將回退到容器驗證,通常使用JaaS來實現。如果你有web.xml,你可以在那裏配置它的基本知識。

然後再次頻繁地進行身份驗證的方式不同。如果您可以手動登錄用戶,例如有可以檢查名稱/密碼的服務,那麼您可以實施一個ContainerRequestFilter,這將填充安全上下文,使得@RolesAllowed註釋可以正常工作。

例如:

更新基於意見

用戶種源方法日誌:

@Path("some/login/path") 
public void login() { 
    String name = getUsernameFromRequest(); 
    String password = // like above 
    User user = loginService.login(name, password); 
    request.getSession().addAttribute("user", user); 
} 

初始化安全上下文中的過濾器的所有請求。

@Priority(Priorities.AUTHENTICATION) 
public class JerseySecurityContextFilter implements ContainerRequestFilter { 

    public void filter(final ContainerRequestContext context) throws IOException { 
    User user = getUserFromSession(); 
    if (user != null) { 
     // this sets security context for the rest of processing 
     // it should make @RolesAllowed work 
     context.setSecurityContext(new JerseySecurityContext(user); 
    } 
} 

final class JerseySecurityContext implements SecurityContext { 

    private final User user; 

    public JerseySecurityContext(final User user) { 
     this.user = user; 
    } 

    public boolean isUserInRole(final String roleName) { 
     return user.hasRole(roleName); 
    } 

    public Principal getUserPrincipal() { 
     return new Principal() { 
      public String getName() { 
       return user.getName(); 
      } 
     }; 
    } 

    public String getAuthenticationScheme() { 
     return null; 
    } 
} 

如果您願意使用JAAS,那麼你就必須在你的應用程序配置配置安全性。這些是嵌入式Jetty的一些示例。

+0

初始化現在,我得到了一個名爲loginUser的資源方法,得到一個dropwizard的應用程序類用戶名和密碼,並檢查它是否與數據庫中的相匹配。如何在調用此特定資源類時告訴JerseySecurityContextFilter運行? –

+0

當用戶登錄並且您的資源方法運行時,請創建一個會話並將其放入其中。然後過濾器將能夠檢查用戶是否存在於會話中。如果是的話,他是登錄的,如果不是,他不是。您可以使用幾種方法將過濾器添加到球衣中。其中之一是用'ResourceConfig'註冊過濾器類。 –

+0

我現在意識到我誤導了你,建議在過濾器中登錄用戶。如果你使用了基本身份驗證之類的東西,那很好。如果您使用專用表單或類似登錄方法的資源支持,請將用戶對象放入會話中,並將其從過濾器中的會話中拉出。其餘的可以保持不變。如果您願意,我可以更新代碼示例。 –