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

How to inform OAuth2 API clients about missing credentials?

我使用 Vert.x 构建了一个 REST API 并且想要添加 OAuth2 身份验证。

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

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

如果缺少访问令牌,您应该 return HTTP 400。如果令牌无效,则必须是 HTTP 401,如 https://www.rfc-editor.org/rfc/rfc6750#section-3.1:

所示

3.1. Error Codes

When a request fails, the resource server responds using the
appropriate HTTP status code (typically, 400, 401, 403, or 405) and
includes one of the following error codes in the response:

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.

If the request lacks any authentication information (e.g., the client was unaware that authentication is necessary or attempted using an unsupported authentication method), the resource server SHOULD NOT include an error code or other error information.

For example:

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