简体   繁体   中英

Send custom response when user authentication is unauthorized

I'm following JWT guide for quarkus here . I want to send custom response when UserGroup is not allowed to access an api.

This is the sample shown in the guide.

@GET()
@Path("roles-allowed") 
@RolesAllowed({"Echoer", "Subscriber"}) 
@Produces(MediaType.TEXT_PLAIN)
public String helloRolesAllowed(@Context SecurityContext ctx) {
    Principal caller =  ctx.getUserPrincipal();
    String name = caller == null ? "anonymous" : caller.getName();
    boolean hasJWT = jwt != null;
    String helloReply = String.format("hello + %s, isSecure: %s, authScheme: %s, hasJWT: %s", name, ctx.isSecure(), ctx.getAuthenticationScheme(), hasJWT);
    return helloReply;
}

How do i know if the request is unauthorized so that i can send custom response.

Short answer: now it can not be done. (explanation in UPDATE section)

It looks like it is JEE application, so maybe here is your answer
Or try this . Or add Provider:

@Provider
public class CustomReasonNotAuthorizedException implements ExceptionMapper<NotAuthorizedException> {

    public Response toResponse(NotAuthorizedException bex) {
        return Response.status(Response.Status.UNAUTHORIZED)
                .entity("your text")
                .build();
    }

}

UPDATE

I checked source code and try it in debug and it looks that execution go through this code as below. So you can not change the message "Not authorized".

            HttpAuthenticator authenticator = identity.getAttribute(HttpAuthenticator.class.getName());
            RoutingContext context = ResteasyContext.getContextData(RoutingContext.class);
            if (authenticator != null && context != null) {
                authenticator.sendChallenge(context, null);
            } else {
                respond(requestContext, 401, "Not authorized");
            }

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