聊聊 OAuth 2.0 的 token expire_in 使用

問題背景

有同窗私信問了這樣的問題,訪問 pig4cloud 的演示環境 查看登陸請求 network 返回報文以下:git

{
    "access_token":"16d35799-9cbb-4c23-966d-ab606029a623",
    "token_type":"bearer",
    "refresh_token":"495dbde5-1bbb-43c9-b06b-ecac50aa5d53",
    "expires_in":41000,
    "scope":"server"
}

而本地部署運行的時,登陸請求返回的報文以下:spring

{
    "access_token":"c262afbe-441e-4023-afb4-f88c8a0a7d51",
    "token_type":"bearer",
    "refresh_token":"ea642d50-5cf5-48ad-9ef9-cb57c9dde00a",
    "scope":"server"
}

缺乏 expires_in 過時參數,因此客戶端沒法知悉什麼時候執行刷新行爲。json

源碼剖析

咱們來看下 oauth2 的令牌方法機制,若是客戶端 配置的 validitySeconds (令牌有效期) 大於 0 會返回當前令牌的有效時間 expires_in 參數,服務器

OAuth2AccessToken createAccessToken() {
  DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(UUID.randomUUID().toString());
  int validitySeconds = getAccessTokenValiditySeconds(authentication.getOAuth2Request());
  if (validitySeconds > 0) {
    token.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
  }
  token.setRefreshToken(refreshToken);
  token.setScope(authentication.getOAuth2Request().getScope());

  return accessTokenEnhancer != null ? accessTokenEnhancer.enhance(token, authentication) : token;
}
  • tokenStore 去存儲 令牌的時候,若過時參數爲 0 或者 小於 0 Expiration 爲空,不會設置有效時間也就意味着爲永久有效,因此此時不會客戶端響應 expires_in 參數
if (token.getExpiration() != null) {
  int seconds = token.getExpiresIn();
  conn.expire(accessKey, seconds);
  conn.expire(authKey, seconds);
  conn.expire(authToAccessKey, seconds);
  conn.expire(clientId, seconds);
  conn.expire(approvalKey, seconds);
}

永久有效的令牌是否應該返回 expires_in 參數呢?

咱們先來看下oauth2 協議規範app

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store
Pragma: no-cache

{
  "access_token":"MTQ0NjJkZmQ5OTM2NDE1ZTZjNGZmZjI3",
  "token_type":"bearer",
  "expires_in":3600,
  "refresh_token":"IwOGYzYTlmM2YxOTQ5MGE3YmNmMDFkNTVk",
  "scope":"create"
}
  • access_token (必需) 受權服務器發出的訪問令牌
  • token_type (必需)這是令牌的類型,一般只是字符串「bearer」。
  • expires_in (推薦)若是訪問令牌過時過時時間。
  • refresh_token(可選)刷新令牌,在訪問令牌過時後,可以使用此令牌刷新。
  • scope(可選)若是用戶授予的範圍與應用程序請求的範圍相同,則此參數爲可選。

此處 expires_in 推薦返回,不管是有設置有效期限制仍是無有效期限制。因此此處 spring security oauth2 的處理並不符合協議規範 emmm 。dom

項目推薦: Spring Cloud 、Spring Security OAuth2的RBAC權限管理系統 歡迎關注code

相關文章
相關標籤/搜索