何时将刷新令牌传递给 API

When to pass refresh token to API

我正在尝试访问一个授权服务器,该服务器在用户提供用户名和密码时发出短期访问令牌和长期刷新令牌。

  1. 客户端是否应该在每次调用 API 时将刷新令牌与访问令牌一起传递,或者客户端是否应该仅在收到来自 API 的错误代码后才传递刷新令牌访问令牌已过期?
  2. 刷新令牌过期后,什么类型的错误代码会传回客户端?这意味着客户端需要通过再次传递用户名和密码来请求新的访问令牌。

问题一:

Should the client pass the refresh token on every call to the API along with the access token or should the client only pass the refresh token once they receive an error code from the API that the access token has expired?

在访问令牌过期之前,客户端不需要刷新令牌。 每个调用都需要访问令牌,但只有授予新访问令牌的请求才需要刷新令牌。

要获取新的访问令牌,请发送一个 grant_type 设置为 refresh_token 的请求,如 section 6 of the RFC.
理想情况下,您会在当前访问令牌过期之前请求一个新的访问令牌,以免中断服务。

我见过的大多数实现都使用每个 访问令牌发出一个新的刷新令牌。您可以使用任何有效的刷新令牌来获取新的访问令牌。

问题二:

What type of error code is passed back to the client once the refresh token has expired? This would mean the client needs to request a new access token by passing the username and password again.

不幸的是,RFC 没有明确定义错误响应;请参阅 RFC 的第 7.2 节:

If a resource access request fails, the resource server SHOULD inform the client of the error. While the specifics of such error responses are beyond the scope of this specification, this document establishes a common registry in Section 11.4 for error values to be shared among OAuth token authentication schemes.

因此,确切的响应取决于服务器。它应该由相关服务器定义。

如果服务器提供新的刷新令牌,您将希望在当前刷新令牌过期之前获得一个新的刷新令牌。

您不想再次发送用户的凭据;你不应该拥有它们,更不用说保留它们了。 OAuth 2 旨在允许第三方访问用户的受保护资源而无需查看用户的凭据。

您通常会在 password_grantrefresh_token 调用中获得带有新访问令牌的新刷新令牌。不过,RFC 并不保证这一点。
如果服务器不提供新的刷新令牌,或者不能依赖提供新的刷新令牌,您将不得不要求用户重新登录。请注意,此登录是通过授权服务器完成的,它不一定是您的应用程序。事实上,它可能不是。