gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:54:46 24 4
gpt4 key购买 nike

我正在关注 quarkus 的 JWT 指南 here 。我想在不允许 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;
}

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

最佳答案

简短回答:现在做不到。 (更新部分中有说明)

它看起来像是 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");
}

关于java - 当用户身份验证未经授权时发送自定义响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58445262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com