1

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.

lczapski
  • 4,026
  • 3
  • 16
  • 32
Jithin S
  • 95
  • 8

1 Answers1

0

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");
            }
lczapski
  • 4,026
  • 3
  • 16
  • 32
  • but this can be thrown manually like ```throw new WebApplicationException(Response.Status.NOT_FOUND);``` but in my case roleschecked before entering the function – Jithin S Oct 18 '19 at 11:01
  • Digging in source code i think that it cannot be done. @JithinS – lczapski Oct 18 '19 at 13:18