简体   繁体   中英

Handle unauthorized error message response body in Tomcat

I'm setting up authentication for a portion of a webapp using standard servlet container authentication ( web.xml security entries) plus Tomcat Realm capabilities (to read users and roles from a database).

Everything seems to fit my requirements except one aspect: since the authentication will guard our REST APIs, I'd like every response to be in JSON format.

But with the tools I'm going to use, when there's a failed authentication Tomcat sends back a response with an HTML body.

I found this question on Spring that addresses the same issue, but it relies on Spring components.

Is there any customization possible using only servlet and Tomcat components?

From first glance, simple solution may look like custom error page for error code 401 (or any other). Look for answer there: how to specify the default error page in web.xml

PS Probably you can also use custom Servlet filter to handle content for error.

Because you're using a standard JAX-RS provider you can take advantage of the standards that exist. Normally you'd want something like:

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;


@Provider
public class MyExceptionMapper implements ExceptionMapper<RuntimeException> {

    @Override
    @Produces(MediaType.APPLICATION_JSON)
    public Response toResponse(RuntimeException exception) {

        return Response.status(Response.Status.FORBIDDEN)
                       .entity("{\"error\": \"your error message\"}")
                       .type(MediaType.APPLICATION_JSON)
                       .build();
    }
}

The hard part here is that the exceptions vary between JAX-RS providers. So, while I may get a RuntimeException with RestEasy (and I know that I do) the exception may be different with Jersey. If you implement an exception mapper that just takes Exception you can quickly figure out what type of Exception is thrown with your JAX-RS provider.

The advantage of this is that it is mostly standard in that you could move to another app server and it would not be Tomcat specific.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM