java - 当用户身份验证未授权时发送自定义响应
问题描述
我在 这里关注 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;
}
我如何知道请求是否未经授权,以便我可以发送自定义响应。
解决方案
简短的回答:现在做不到。(更新部分的解释)
看起来它是 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");
}
推荐阅读
- excel - 如何使用 VBA 代码将 .csv 文件的前 5000 行读入 Excel
- python - 查找重复的 id 属性
- .htaccess - 我可以使用 .htaccess 规则使用通配符作为站点,然后重写特定页面吗?
- sql - 仅获取 SQL 中的最后“一批”值
- c# - C# Winforms如何从Datagridview获取文本到基于同一行上另一个单元格的标签?
- c# - .NET SqlCommand.AddWithValue() 的奇怪日期时间格式问题
- python - 使用循环内不同函数的子图创建图形
- mysql - 在 myPhpAdmin 中设置外键
- reactjs - NextJS 图片组件的 PropTypes
- javascript - Simplify switch statement