I need to secure a simple Jersey RESTful API in a Tomcat 6.0.24 container. I\'d like to keep the authentication with Basic Authentication using the tomcat-users.xml
You can start with using a filter which covers the authentication and privilege management at first. with implemeting ResourceFilter and ContainerRequestFilter, you ability to get httpRequest, sessions then redirects your application/requests to related methods.
For privilege management you can implement SecurityContext filter. you have to check isUserInRole at first to let request go inside method.
Here is the sample for SecurityContext implementation:
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;
}
}
Here is the basic SecurityContextFilter implementation :
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;
}
}
Do not forget to put your filter as an init-param inside the web.xml,
Then you can handle request with your role-privilege-authentication logic.