【发布时间】: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