Custom HTTP status response with JAX-RS (Jersey) and @RolesAllowed

前端 未结 3 1591
借酒劲吻你
借酒劲吻你 2020-12-28 08:00

With my very simple JAX-RS service I\'m using Tomcat with JDBC realm for authentication, therefore I\'m working the the JSR 250 annotations.

The thing is that I want

相关标签:
3条回答
  • 2020-12-28 08:46

    The easiest way to handle this sort of thing is to throw an exception and to register an exception mapper to convert into the kind of message you want to send in that case. So, suppose you throw an AccessDeniedException, you would then have a handler like this (with full class names in places for clarity):

    @javax.ws.rs.ext.Provider
    public class AccessDeniedHandler
            implements javax.ws.rs.ext.ExceptionMapper<AccessDeniedException> {
        public javax.ws.rs.core.Response toResponse(AccessDeniedException exn) {
            // Construct+return the response here...
            return Response.status(403).type("text/plain")
                    .entity("get lost, loser!").build();
        }
    }
    

    The way in which you register the exception mapper varies according to the framework you're using, but for Jersey you should be fine with just using @Provider. I'll let you figure out for yourself how you want to generate the kind of error documents that you want, but I do recommend handling failures as HTTP error codes of some kind (that's more RESTful...)

    0 讨论(0)
  • 2020-12-28 08:47

    REST is build upon HTTP so you don't have to change the default behavior of an authentication failure. Having a 403 error when accessing a resource is enough for the client to clearly understand what appends.

    The more your resources are HTTP compliant, the more others can understand it.

    0 讨论(0)
  • 2020-12-28 09:01

    With creating an ExceptionMapper (mapping exceptions of WebApplicationException) it is possible to "catch" certain exceptions thrown by the application:

    @Provider
    public class MyExceptionMapper implements ExceptionMapper<WebApplicationException> {
    
        @Override
        public Response toResponse(WebApplicationException weException) {
    
            // get initial response
            Response response = weException.getResponse();
    
            // create custom error
            MyError error = ...;
    
            // return the custom error
            return Response.status(response.getStatus()).entity(error).build();
        }
    }
    

    You also need to add the package to your application web.xml for registering the provider:

    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>
            com.myapp.userservice; // semi-colon seperated
            com.myapp.mappedexception
        </param-value>
    </init-param>
    
    0 讨论(0)
提交回复
热议问题