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

前端 未结 3 1594
借酒劲吻你
借酒劲吻你 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 {
        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...)

提交回复
热议问题