我试图保护JAX-RS端点,并且正在试图弄清楚认证和授权如何工作。大多数示例都非常简单,因为它们只通过web.xml从Java EE App-Server角色搭载。JAX-RS和自定义授权
我想知道如何使用比Java EE AS角色更多的东西。例如:我想使用会话或某种标记(或某种标识符)。
我试图保护JAX-RS端点,并且正在试图弄清楚认证和授权如何工作。大多数示例都非常简单,因为它们只通过web.xml从Java EE App-Server角色搭载。JAX-RS和自定义授权
我想知道如何使用比Java EE AS角色更多的东西。例如:我想使用会话或某种标记(或某种标识符)。
这一切都取决于您使用的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
一旦你在HttpServletRequest
的Principal
,你可以注入到这些的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
}
}
声明:除非你真的,真的,真的需要你自己的安全框架,否则不要扮演你自己的安全框架。
看看泽西岛的OAuth filter在做什么。它读取授权标头,该标头以不同于通常理解的格式(HTTP基本)保存凭证。如果你添加了Roles Allowed Filter,那么它将把这些凭证变成角色,然后你可以使用它来实现安全性(@RolesAllowed)。试着看看这些过滤器是如何工作的。