未经授权的用户身份验证时发送自定义响应

时间:2019-10-18 06:41:06

标签: java jwt jwt-auth quarkus

我正在遵循有关J夸特here的JWT指南。我想在不允许UserGroup访问api时发送自定义响应。

这是指南中显示的示例。

@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;
}

我怎么知道请求是否未经授权,以便我可以发送自定义响应。

1 个答案:

答案 0 :(得分:0)

简短的回答:现在无法完成。 (UPDATE部分中的说明)

它看起来像是JEE应用程序,所以也许here is your answer
或尝试this。 或添加提供者:

@Provider
public class CustomReasonNotAuthorizedException implements ExceptionMapper<NotAuthorizedException> {

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

}

更新

我检查了源代码,并在调试中尝试了一下,它看起来执行通过了this code,如下所示。因此,您无法更改消息“未授权”。

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