I am trying to implement user authentication for rest calls in jersey 1.11 filters.
This is what i have tried
package com.ilrn.session.webservices.rest.filter;
import com.ilrn.entity.User;;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
public class CustomFilter implements ContainerRequestFilter{
@Override
public ContainerRequest filter(ContainerRequest request) {
User user = Helper.getCurrentUser();
if(user == null){
//Need to add custom response and abort request
}
return request;
}
}
Does anyone know any method or something to achieve the same?
In case of error, if you want to send a custom response then you need to throw a WebApplicationException. Create a Response object and send it back using the following exception constructor:
WebApplicationException(Response response)
Construct a new instance using the supplied response
Try this:
@Override
public ContainerRequest filter(ContainerRequest request) {
User user = Helper.getCurrentUser();
if(user == null){
ResponseBuilder builder = null;
String response = "Custom message";
builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
throw new WebApplicationException(builder.build());
}
return request;
}