2017-07-07 119 views
0

我目前正在一個完全模塊化的應用程序,我們有很多罐子將被打包並粘在一起的戰爭文件。@RolesAllowed等沒有web.xml

其中一些jar文件具有要保護的REST資源。常見的方法是@RolesAllowed註釋等。

從我目前的知識來看,這意味着WAR中存在的web.xml。這樣我們就必須在WAR內部實現特定於jar的信息(例如上下文根),而不是它所屬的地方。

像現在的大多數事情一樣 - 有沒有一種方法來編程設置安全上下文等沒有web.xml?

回答

0

您可以通過從ResourceConfig

public class ApplicationConfig extends ResourceConfig { 
    public ApplicationConfig() { 
    super(ApplicationConfig.class); 
    register(RolesAllowedDynamicFeature.class); 
    } 
} 

延伸,你可以使用你的應用程序角色上的資源的方法是這樣

import javax.annotation.security.PermitAll; 
import javax.annotation.security.RolesAllowed; 
import javax.ws.rs.GET; 
import javax.ws.rs.Path; 
import javax.ws.rs.core.Context; 
import javax.ws.rs.core.SecurityContext; 

@Path("secured") 
@PermitAll 
public class SecuredResource { 

    @GET 
    @Path("user") 
    @RolesAllowed("user") 
    public String user(@Context SecurityContext sc) { 
    boolean test = sc.isUserInRole("user"); 
    return (test) ? "true": "false"; 
    } 

    @GET 
    @Path("admin") 
    @RolesAllowed("admin") 
    public String admin(@Context SecurityContext sc) { 
    boolean test = sc.isUserInRole("admin"); 
    return (test) ? "true": "false"; 
    } 
} 
您的REST配置類註冊 RolesAllowedDynamicFeature限制訪問您的REST資源

澤西島文檔有更多關於在這裏使用註釋來保護REST資源的詳細信息

https://jersey.github.io/documentation/latest/security.html#d0e12428