外部身份验证失败时 return 的哪个 HTTP 状态?

Which HTTP Status to return when external authentication fails?

在我的 ASP.NET MVC web 应用程序中,我有一个外部单点登录,用于在企业中集中验证用户。 SSO 应该 return 一个 "packet" 唯一标识用户的东西,然后将用于传递给本地 ASP.NET Owin Cookie 身份验证(或者表单身份验证,或类似的东西那)。如果出于某种原因,SSO 提供的 "packet" 内容不包含最低要求的信息,我想在本地 ASP.NET 级别适当地处理它。这是一个非常严重的错误,不一定会经常发生。所以我想我会做这样的事情:

public class AuthController() : Controller
{
    public ActionResult Login(string returnUrl)
    {
        // Process external single-sign-on authentication
        bool isSuccess = ProcessExternalAuth();
        if (!success)
            // return appropriate HTTP status code
        else
            // continue with login
    }
}

但我不确定 return 的 HTTP 状态代码。这样的事情合适吗?

return new HttpStatusCodeResult(
    HttpStatusCode.BadGateway, "SSO authentication failed.");

根据 List of HTTP Status Codes,500 个错误之一可能是最合适的:

Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has encountered an error or is otherwise incapable of performing the request...

错误代码 401 和错误代码 403 通常用于与身份验证相关的错误。然而,它们有一些与之配套的标准,这些标准指定了何时以及如何使用它们。在您的例子中,这些都不适合。例如,403 被描述为 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html):

403 Forbidden

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

return 代码 503(服务不可用)是一个不错的选择。

503 Service Unavailable

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.

验证客户端的错误应低于 401:

401 未经授权 (RFC 7235)

类似于 403 Forbidden,但专门用于需要身份验证但失败或尚未提供的情况。响应必须包含一个 WWW-Authenticate 头字段,其中包含适用于所请求资源的质询。请参阅基本访问身份验证和摘要访问身份验证。 [36] 401 在语义上意味着 "unauthenticated",即用户没有必要的凭据。 注意:某些网站在网站禁止 IP 地址(通常是网站域)并且拒绝访问网站的特定地址时发出 HTTP 401。

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#4xx_Client_Error