Search code examples
javasecurityjakarta-eejerseyejb

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


I get the exception:

Warning:   StandardWrapperValve[org.netbeans.rest.application.config.ApplicationConfig]: Servlet.service() for servlet org.netbeans.rest.application.config.ApplicationConfig threw exception
javax.ejb.AccessLocalException: Client not authorized for this invocation

This is perfectly normal, as it is not authorized for this methodcall.

Onfortunately, as this EJB is a REST Service as well, it throws a "500 - Bad Request" http status. Instead I would like to have a "401 - Unauthorized".

Should I not use EJB Security or should I catch this AccessLocalException in the ApplicationConfig or should I use Jersey to implement REST Security?

Roles are defined in the web.xml and annotations are put upon the EJB Bean.


Solution

  • You can define an ExceptionMapper, that maps a General Exception onto a 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();
      }
    }