問題描述
為什麼每次發送請求時都刷新訪問令牌是個壞主意? (Why is it a bad idea to refresh access token every time when I sent request?)
當我登錄我的應用程序時,我正在對本機應用程序進行反應並使用 OAuth2 並獲取訪問令牌、刷新令牌並及時過期。我在發送請求(GET、POST)時檢查了我的令牌是否及時過期。如果我的令牌過期,那麼我使用刷新令牌來獲取新的訪問令牌。我的同事告訴我,我不需要檢查過期時間,只需在每次發送請求時使用刷新令牌來獲取訪問令牌。我知道他的方式不對,但如果我用他的方式會發生什麼?為什麼每次發送請求都刷新訪問令牌不好?
參考解法
方法 1:
Because it increases the network round trips and makes your application slower than it needs to be, and increases the load on the token service.
That way lies scaling problems and terrible user experience.
方法 2:
Your co‑worker probably advised you to do this, which is how I always code these things:
- Send the current access token to the API on each request
- Eventually the access token will return 401
- Then use the refresh token to get a new access token + retry the API call
- Eventually the token renewal request will fail with an invalid_grant error and the user has to login again
That is, you refresh only when the access token expires and not on every single request. You avoid relying on the access token expiry time, since APIs can reject tokens for multiple reasons.
(by kiritoty、Josh Wulf、Gary Archer)