JAX-RS和自定义授权

我正在尝试保护JAX-RS端点,目前正在尝试弄清楚身份validation和授权是如何工作的。 大多数示例都非常简单,因为它们只能通过web.xml从Java EE App-Server角色中捎带。

我想知道如何使用除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()); 

请参见如何使用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 } } 

免责声明:除非您真的,真的,真的需要,否则不要对自己的安全框架进行角色扮演。

看看泽西岛的OAuthfilter做了什么。 它读取Authorization标头,该标头以不同于通常理解的格式(HTTP Basic)的格式保存凭据。 它会将这些凭据转换为角色,然后您可以使用它来实现安全性(@RolesAllowed),如果您添加了允许实际执行的角色允许filter 。 尝试查看这些filter的工作原理。