【问题标题】:JAX-RS and custom authorizationJAX-RS 和自定义授权
【发布时间】:2011-07-04 02:39:55
【问题描述】:

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

我想知道如何使用 Java EE AS 角色以外的其他东西。例如:我想使用会话或某种令牌(或某种标识符)。

【问题讨论】:

    标签: java jax-rs restful-authentication


    【解决方案1】:

    这完全取决于您使用的 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
        }
    }
    

    【讨论】:

      【解决方案2】:

      免责声明:除非您真的、真的、真的需要一个,否则不要扮演您自己的安全框架。

      看看泽西岛的OAuth filter 是做什么的。它读取 Authorization 标头,该标头以与通常理解的格式(HTTP Basic)不同的格式保存凭据。如果您添加执行实际执行的Roles Allowed Filter,它会将这些凭据转换为您可以用来实现安全性(@RolesAllowed)的角色。试着看看这些过滤器是如何工作的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-15
        • 2015-06-28
        • 2015-01-22
        • 2013-03-15
        • 2018-02-01
        • 2012-02-10
        • 2012-07-27
        • 1970-01-01
        相关资源
        最近更新 更多