使用 JAX-RS (Jersey) 和 @RolesAllowed 自定义 HTTP 状态响应

2022-01-21 00:00:00 java jax-rs jersey jsr250

通过我非常简单的 JAX-RS 服务,我使用带有 JDBC 领域的 Tomcat 进行身份验证,因此我正在使用 JSR 250 注释.

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.

问题是我想在 HTTP 状态响应中返回一个自定义消息体.状态码 (403) 应该保持不变.例如,我的服务如下所示:

The thing is that I want to return a custom message body in the HTTP status response. The status code (403) should stay the same. For example, my service looks like the following:

@RolesAllowed({ "ADMIN" })
@Path("/users")
public class UsersService {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public String getUsers() {
        // get users ...
        return ...;
    }
}

如果具有不同于ADMIN"角色的用户访问服务,我想将响应消息更改为类似的内容(取决于媒体类型 [xml/json]):

If a user with a different role than "ADMIN" access the service, I want to change the response message to something like that (depending on the media type [xml/json]):

<error id="100">
    <message>Not allowed.</message>
</error>

此时 Jersey 返回以下正文:

At the moment Jersey returns the following body:

HTTP Status 403 - Forbidden

type Status report
message Forbidden
description Access to the specified resource (Forbidden) has been forbidden.
Apache Tomcat/7.0.12

如何更改默认邮件正文?有没有办法处理(可能抛出的)异常来构建我自己的 HTTP 状态响应?

How can I change the default message body? Is there a way to handle the (maybe thrown) exception to build my own HTTP status response?

推荐答案

处理这类事情的最简单方法是抛出一个异常并注册一个异常映射器以转换为您要发送的消息类型案件.所以,假设你抛出一个AccessDeniedException,你就会有一个像这样的处理程序(为了清楚起见,在一些地方有完整的类名):

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();
    }
}

您注册异常映射器的方式因您使用的框架而异,但对于泽西岛,您只需使用 @Provider 就可以了.我会让你自己弄清楚你想如何生成你想要的那种错误文档,但我确实建议将失败处理为某种 HTTP 错误代码(这更符合 RESTful...)

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...)

相关文章