2011-02-25 59 views
6

我試圖保護JAX-RS端點,並且正在試圖弄清楚認證和授權如何工作。大多數示例都非常簡單,因爲它們只通過web.xml從Java EE App-Server角色搭載。JAX-RS和自定義授權

我想知道如何使用比Java EE AS角色更多的東西。例如:我想使用會話或某種標記(或某種標識符)。

回答

7

這一切都取決於您使用的JAX-RS實現。我在嵌入Jetty上使用Jersey

SecurityHandler sh = new SecurityHandler(); 

// the UserRealm is the collection of users, and a mechanism to determine if 
// provided credentials are valid 
sh.setUserRealm(new MyUserRealm()); 

// the Authenticator is a strategy for extracting authentication credentials 
// from the request. BasicAuthenticator uses HTTP Basic Auth 
sh.setAuthenticator(new BasicAuthenticator()); 

How to Configure Security with Embedded Jetty

一旦你在HttpServletRequestPrincipal,你可以注入到這些的JAX-RS請求的上下文。

public abstract class AbstractResource { 
    private Principal principal; 
    @Context 
    public void setSecurityContext(SecurityContext context) { 
     principal = context.getUserPrincipal(); 
    } 
    protected Principal getPrincipal() { 
     return principal; 
    } 
} 

@Path("/some/path") 
public class MyResource extends AbstractResource { 
    @GET 
    public Object get() { 
     Principal user = this.getPrincipal(); 
     // etc 
    } 
} 
2

聲明:除非你真的,真的,真的需要你自己的安全框架,否則不要扮演你自己的安全框架。

看看澤西島的OAuth filter在做什麼。它讀取授權標頭,該標頭以不同於通常理解的格式(HTTP基本)保存憑證。如果你添加了Roles Allowed Filter,那麼它將把這些憑證變成角色,然後你可以使用它來實現安全性(@RolesAllowed)。試着看看這些過濾器是如何工作的。