首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >.net如何在授权失败时设置响应体?

.net如何在授权失败时设置响应体?
EN

Stack Overflow用户
提问于 2022-01-27 19:54:25
回答 1查看 200关注 0票数 1

当授权在我的API中失败时,我必须显示自定义(Json)响应体。默认情况下,我有这样的消息:未经授权。但我想返回一个包含自定义代码错误、消息和其他细节的json。这是我所做的一个例子。

代码语言:javascript
运行
复制
                o.Events = new JwtBearerEvents
            {
                OnChallenge = async (context) =>
                {
                    if (!context.Request.Headers.ContainsKey("Authorization"))
                    {
                        context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The authorization parameter is not given or the token passed is empty";
                    }
                },
                OnAuthenticationFailed = async (context) =>
                {
                    await context.HttpContext.Response.WriteAsync("ramses");
                    context.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "The token is invalid or has expired";
                },
            };

我尝试使用WriteAsync方法的HttpContext.Response,但我定义的消息没有出现,只有原因短语出现正确。

这是我的API中结果的图像。

我在startup.cs的jwtBearer配置中指定了这段代码

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-27 20:15:20

我在我的代码中使用了这个,它运行得很好

代码语言:javascript
运行
复制
.AddJwtBearer(o => {
    
   o.RequireHttpsMetadata = false;
   o.SaveToken = false;
   o.TokenValidationParameters = tokenValidationParameters;
   
   o.Events = new JwtBearerEvents {
       
        OnAuthenticationFailed = c => {

            c.NoResult();
            c.Response.StatusCode = 500;
            c.Response.ContentType = "text/plain";

            return c.Response.WriteAsync(c.Exception.ToString());
        },
        
        OnChallenge = context => {

            context.HandleResponse();
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";

            var result = JsonConvert.SerializeObject(new {
               status = "un-authorized",
               message = "un-authorized"
            });

            return context.Response.WriteAsync(result);
        },
        
        OnForbidden = context => {

            context.Response.StatusCode = 403;
            context.Response.ContentType = "application/json";

            var result = JsonConvert.SerializeObject(new {
               status = "un-authorized",
               message = "un-authorized"
            });

            return context.Response.WriteAsync(result);
        }
        
   };
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70884906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档