如何通知 OAuth2 API 客户端缺少凭据?



我使用 Vert.x 构建了一个 REST API,并希望添加 OAuth2 身份验证。

在我当前的设置中,未经身份验证的请求将自动重定向到 OAuth2 服务器(密钥斗篷(登录页面。这在处理 REST API 时似乎是错误的。相反,我希望我的 REST API 服务器返回 401,从而让客户端处理获取访问令牌的过程。

此用例是否有最佳实践?如何处理对受保护资源的未经身份验证的请求?

缺少访问令牌时,应返回 HTTP 400。如果令牌无效,则必须为 HTTP 401,如 https://www.rfc-editor.org/rfc/rfc6750#section-3.1 所示:

3.1. 错误代码

当请求失败时,资源服务器将使用
适当的 HTTP 状态代码(通常为 400、401、403 或 405(进行响应,并且
在响应中包含以下错误代码之一:

invalid_request

The request is missing a required parameter, includes an
unsupported parameter or parameter value, repeats the same
parameter, uses more than one method for including an access
token, or is otherwise malformed.  The resource server SHOULD
respond with the HTTP 400 (Bad Request) status code.

invalid_token

The access token provided is expired, revoked, malformed, or
invalid for other reasons.  The resource SHOULD respond with
the HTTP 401 (Unauthorized) status code.  The client MAY
request a new access token and retry the protected resource
request.

insufficient_scope

The request requires higher privileges than provided by the
access token.  The resource server SHOULD respond with the HTTP
403 (Forbidden) status code and MAY include the "scope"
attribute with the scope necessary to access the protected
resource.

如果请求缺少任何身份验证信息(例如, 客户端不知道身份验证是必要的或尝试的 使用不受支持的身份验证方法(,资源服务器 不应包含错误代码或其他错误信息。

例如:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="example"

最新更新