简体   繁体   English

在 ASP.NET Web API Core 中,如何强制 401 响应

[英]In ASP.NET Web API Core, how can I force a 401 response

I am using OAuth2 and OIDC in my ASP.NET Core Web API Service.我在我的 ASP.NET Core Web API 服务中使用 OAuth2 和 OIDC。 When I get a JWT token in, it validates it.当我收到 JWT 令牌时,它会对其进行验证。

In my case, my Issuer is not matching.就我而言,我的发行人不匹配。 I am able to see this because the results of the validation are surfaced in the JwtBearerEvents event OnAuthenticationFailed .我能够看到这一点,因为验证结果显示在JwtBearerEvents事件OnAuthenticationFailed That is the point where I can know that I need to return 401.这就是我可以知道我需要返回 401 的地方。

How can I set my service to return 401 at that point?我如何设置我的服务在那时返回 401?

I haven't had a chance to test this in a real project, but if you just want to return a 401, then you might want to try something like:我还没有机会在实际项目中对此进行测试,但是如果您只想返回 401,那么您可能想尝试以下操作:

OnAuthenticationFailed = context =>
{
    context.Response.StatusCode = 401; 
    context.Response.WriteAsync("Unauthorized").Wait();
    return Task.CompletedTask;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我应该如何在 asp.net 核心 web api 中发送 401 和 403 响应代码? - How should i send 401 and 403 response code in asp.net core web api? ASP.Net / ASP.NET 核心 Web API 未经授权的请求返回 302 重定向响应而不是 401 - ASP.Net / ASP.NET Core Web API unauthorized requests returns 302 redirect response instead of 401 如何在ASP.NET Core Web API响应中忽略ResponseWrapper - How to ignore ResponseWrapper in ASP.NET Core Web API response ASP.NET 内核 Web API 如何使用 try catch 方法捕获 401 和 403 错误 - ASP.NET Core Web API how to catch the 401 and 403 errors using the try catch method 在 ASP.Net Core Web 服务中,如何测量通过网络发送响应所需的时间? - In a ASP.Net Core Web service, how can I measure the time required to send the response over the network? 如何在ASP.NET Core Web Api中完成版本控制 - How can versioning be done in ASP.NET Core Web Api ASP.NET Core Web API 使用客户端证书调用其他 Web API 获取 401 - ASP.NET Core Web API calling other Web API using Client Certificate getting 401 如何使用 asp.net core 在 JSON web api 请求中捕获包含的属性名称? - How can I capture included property names in a JSON web api request with asp.net core? 如何在 ASP.NET Core Web API 中配置 JSON 格式的缩进 - How can i configure JSON format indents in ASP.NET Core Web API 如何在asp.net核心中为“ Web”和“ API”创建路由 - How can I create routes for “web” and “api” in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM