【发布时间】:2011-07-04 02:39:55
【问题描述】:
我正在尝试保护 JAX-RS 端点,目前正在尝试弄清楚身份验证和授权是如何工作的。大多数示例都非常简单,因为它们只是通过 web.xml 从 Java EE App-Server 角色捎带。
我想知道如何使用 Java EE AS 角色以外的其他东西。例如:我想使用会话或某种令牌(或某种标识符)。
【问题讨论】:
标签: java jax-rs restful-authentication
我正在尝试保护 JAX-RS 端点,目前正在尝试弄清楚身份验证和授权是如何工作的。大多数示例都非常简单,因为它们只是通过 web.xml 从 Java EE App-Server 角色捎带。
我想知道如何使用 Java EE AS 角色以外的其他东西。例如:我想使用会话或某种令牌(或某种标识符)。
【问题讨论】:
标签: java jax-rs restful-authentication
这完全取决于您使用的 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 是做什么的。它读取 Authorization 标头,该标头以与通常理解的格式(HTTP Basic)不同的格式保存凭据。如果您添加执行实际执行的Roles Allowed Filter,它会将这些凭据转换为您可以用来实现安全性(@RolesAllowed)的角色。试着看看这些过滤器是如何工作的。
【讨论】: