【问题标题】:Java Restful Web Services (jax rs) authentication patternJava Restful Web Services (jax rs) 身份验证模式
【发布时间】:2011-10-13 16:04:58
【问题描述】:

我已经开始使用 JAX-RS 为我的 Web 应用程序创建一个简单的 Restful 界面。目前,它仅由一个可以访问所有应用程序数据的内部客户端使用(只读),并且我正在使用 http 基本身份验证进行访问。我想开始将它用作我的应用程序视图层的一部分,并且只有当用户通过 Web 应用程序登录时才允许某些操作。我正在努力寻找一种模式,允许我以优雅的方式使用两种形式的身份验证,而无需重复大量代码。这是我想出的大致内容:

首先是一个用于加载应用程序会话的 util 类,它存储在数据库中。

public class RestUtil {
    public static AppSession getAuthenticatedSession(HttpServletRequest request) {
        AppSession session;
        String remoteUser = request.getRemoteUser();
        if (remoteUser != null) {
            session = SessionRepository.loadSessionByRemoteUser(remoteUser);
        } else {
            session = SessionRepository.loadSessionById(request.getSession().getId());
        }
        return session;
    }
}

这是我们的资源,其中一种方法只能由经过身份验证的用户或我们的 http 基本身份验证客户端访问:

@Path("/protected/resource")
public class ProtectedResource {
    @GET
    @Produces(MediaType.TEXT_JSON)
    @Path("{userId}")
    public String getProtectedResourceJson(@Context HttpServletRequest request, @PathParam("userId") Integer userId) {
        // Return Charity List XML
        AppSession session = RestUtil.getAuthenticatedSession(request);

        if (session.canAccessUser(userId))  //get Json...
    }
}

这里是 AppSession 最基本的视图,为了这个问题的目的:

public class AppSession {
    User authenticatedUser;
    String remoteUser;

    public boolean canAccessUser(Integer userId) {
        if (remoteUser != null) {
            //this client has access to all users
            return true;
        } else if (authenticatedUser.getId().equals(userId)) {
            //this is local client, calling the service from a view
            //only has access to authenticatedUser
            return true;
        } else {
            return false;
        }
    }
}

此外,对于不需要任何类型身份验证的服务,我如何防止未经授权的第三方仅指向 url,并在闲暇时获取数据?

【问题讨论】:

    标签: java design-patterns jax-rs restful-authentication


    【解决方案1】:

    您已经到了值得研究使用面向方面编程将事物的安全方面与业务逻辑分开的地步。如果您已经在使用 Spring 来组装应用程序的各个部分(我建议将其用于复杂的服务器),那么只需添加 Spring AOP 来注入安全逻辑即可。否则,直接使用 AspectJ。处理多种登录模式的实际逻辑可能必须是自定义的,但至少您可以将其隔离。

    如果使用 Spring,请考虑使用 Spring Security;它构建在 Spring AOP 之上,为您提供更多解决方案。

    【讨论】:

    • 要是我们有春天就好了。从好的方面来说,我一直想找个借口来研究aspectj。
    猜你喜欢
    • 2015-12-18
    • 2016-06-08
    • 2011-04-22
    • 1970-01-01
    • 2012-02-10
    • 2011-11-16
    • 2018-11-30
    • 1970-01-01
    • 2020-11-13
    相关资源
    最近更新 更多