Thursday, 15 June 2017

REST-EJB AccessLocalException causes BadRequest(500) instead of Unauthorized(401)

I am using EJBs as REST Services. It works pretty well. I added security on the EJB, by means of security definitions in the web.xml file and appropriate annotations on the EJB (@DeclareRoles and @RolesAllowed).

Unfortunately, when I try to access the methods in the EJB without being properly authorized, I received a 500 BadRequest. Instead I would really like to have a 401 Unauthorized.

I posted a question on StackOverflow1, but I have found the solution2 in the mean time, which I also posted, and will repost here.

It is possible to add an ExceptionMapper to your Application, which can map between an Exception and an appropriate HTTP Response.
import javax.ejb.EJBAccessException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class EJBAccessExceptionMapper implements
ExceptionMapper<EJBAccessException>
{
@Override
public Response toResponse(EJBAccessException exception)
{
return Response.status(Response.Status.UNAUTHORIZED).build();
}
}

Note

My ApplicationConfig has now been expanded with a
resources.add(mmud.exceptions.EJBAccessExceptionMapper.class);
.

References

[1] StackOverflow - REST-EJB AccessLocalException causes BadRequest(500) instead of Unauthorized(401)
https://stackoverflow.com/questions/44351224/rest-ejb-accesslocalexception-causes-badrequest500-instead-of-unauthorized401
[2] RESTfu­­l Jav­a­ wit­h ­JAX­-­­RS 2.­0­ (Second Edition) - Exception Handling
https://dennis-xlc.gitbooks.io/restful-java-with-jax-rs-2-0-2rd-edition/en/part1/chapter7/exception_handling.html
StackOverflow -
https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses

No comments:

Post a Comment