您可以首先使用涵盖身份验证和权限管理的过滤器。通过实现 ResourceFilter 和 ContainerRequestFilter,您可以获取 httpRequest,会话然后将您的应用程序/请求重定向到相关方法。
对于权限管理,您可以实现 SecurityContext 过滤器。你必须首先检查 isUserInRole 让请求进入方法。
这是 SecurityContext 实现的示例:
public class SecurityContextImpl implements SecurityContext {
private final SessionUser user;
public SecurityContextImpl(SessionUser user) {
this.user = user;
}
public Principal getUserPrincipal() {
return user;
}
public boolean isUserInRole(String role) {
if(user == null) {
throw new AuthenticationException();
}
if(ObjectUtil.isNull(user.getPrivileges())){
throw new AuthenticationException();
}
if(!user.getPrivileges().contains(role)) {
throw new InvalidAuthorizationHeaderException();
}
return user.getPrivileges().contains(role);
}
public boolean isSecure() {
return false;
}
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
}
这是基本的 SecurityContextFilter 实现:
public class SecurityContextFilter implements ResourceFilter, ContainerRequestFilter {
private static final Logger LOG = LoggerFactory.getLogger(SecurityContextFilter.class);
protected static final String HEADER_AUTHORIZATION = "Authorization";
protected static final String HEADER_DATE = "x-java-rest-date";
protected static final String HEADER_NONCE = "nonce";
private HttpServletRequest httpRequest;
public SecurityContextFilter() {
}
public ContainerRequest filter(ContainerRequest request) {
SessionUser sessionUser = (SessionUser) httpRequest
.getSession()
.getAttribute("sessionUser");
request.setSecurityContext(new SecurityContextImpl(sessionUser));
return request;
}
public ContainerRequestFilter getRequestFilter() {
return this;
}
public ContainerResponseFilter getResponseFilter() {
return null;
}
public HttpServletRequest getHttpRequest() {
return httpRequest;
}
public void setHttpRequest(HttpServletRequest httpRequest) {
this.httpRequest = httpRequest;
}
}
不要忘记将您的过滤器作为 init-param 放在 web.xml 中,
然后,您可以使用您的角色-特权-身份验证逻辑来处理请求。