【问题标题】:How to send AuthenticateResult.Fail(failure reason), failure reason to to Response body如何将 AuthenticateResult.Fail(失败原因)、失败原因发送到响应正文
【发布时间】:2019-10-02 13:33:29
【问题描述】:

在我的 ASP.NET Core WebAPI 应用程序中,我使用自定义身份验证中间件对请求进行身份验证。一切正常,但我不知道失败原因将如何在响应对象中发送给用户。

    protected override  Task<AuthenticateResult> HandleAuthenticateAsync()
    {
    var token = headers["Authorization"].ToString();
                if (string.IsNullOrEmpty(token))
                {
    return  Task.FromResult(AuthenticateResult.Fail("Token is null"));
    
    }

}

我试过了:

Task callTask = Task.Run(
                    async () => await Context.Response.WriteAsync(errorResult).ConfigureAwait(false));


                if (callTask.IsCompletedSuccessfully)
                {
                    callTask.Wait();
                }

但是在 fiddler 中得到 504 状态码

[Fiddler] ReadResponse() 失败:服务器没有为此请求返回完整的响应。服务器返回 379 字节。

这个失败原因“令牌为空”将如何发送到响应。

【问题讨论】:

  • fiddler 说服务器返回了什么(原始标头和正文)?
  • HTTP/1.1 504 Fiddler - 接收失败 Content-Type: text/html;连接:关闭 [Fiddler] ReadResponse() 失败:服务器没有为此请求返回完整的响应。服务器返回 379 个字节。

标签: asp.net-core asp.net-core-webapi fiddler


【解决方案1】:

您可以使用中间件来自定义未经授权的响应正文。你把它放在 Startup.cs 中的 UseRoutingUseAuth* 调用之间

// Your Configure method in Startup.cs

app.UseRouting();

app.Use(async (context, next) =>
{
    await next();

    if (context.Response.StatusCode == (int) HttpStatusCode.Unauthorized)
    {
        context.Response.ContentType = "text/plain";
        await context.Response.WriteAsync("some custom message");
    }
});

app.UseAuthentication();
app.UseAuthorization();

中间件将请求传递给下一个处理程序,等待它,然后检查响应代码,如果是 401,则修改响应正文。 别忘了设置响应内容类型,这里很重要

基本上,您可以在此处放置任何逻辑。例如,在身份验证处理程序中,您可以使用未经授权的原因设置自定义响应标头:

Response.Headers.Add("X-Custom-Unathorized-Reason", "...");

然后在中间件中访问这条消息:

var reason = context.Response.Headers["X-Custom-Unathorized-Reason"];
context.Response.ContentType = "text/plain";
await context.Response.WriteAsync(reason);

【讨论】:

  • 还有一个modern way 可以通过IAuthorizationMiddlewareResultHandler 执行此操作。但它仅适用于 .NET 5/6
猜你喜欢
  • 2013-06-26
  • 2014-06-14
  • 2011-11-23
  • 2013-12-22
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多