首页 > 解决方案 > 当用户身份验证未授权时发送自定义响应

问题描述

我在 这里关注 quarkus 的 JWT 指南。当不允许用户组访问 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;
}

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

标签: javajwtjwt-authquarkus

解决方案


简短的回答:现在做不到。(更新部分的解释)

看起来它是 JEE 应用程序,所以也许这是你的答案
或者试试这个。或添加提供者:

@Provider
public class CustomReasonNotAuthorizedException implements ExceptionMapper<NotAuthorizedException> {

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

}

更新

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

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

推荐阅读