`

OAuth2.0授权学习——3,更新access token

阅读更多

当access token过期后,可以通过refresh token去请求更新access token,当然需要服务器端支持这个逻辑,OAuth2.inc中已经有了相应代码。添加mongooauth驱动中对grant_type的支持

 

  /**
   * Overrides OAuth2::getSupportedGrantTypes().
   */
  protected function getSupportedGrantTypes() {
    return array(
      OAUTH2_GRANT_TYPE_AUTH_CODE,
      OAUTH2_GRANT_TYPE_USER_CREDENTIALS,
      OAUTH2_GRANT_TYPE_REFRESH_TOKEN
    );
  }

 

然后按照前面的流程获取access token,返回结果如下:

 

 

{
    "access_token":"d9908d26b64e1dc939d1aff7e9a05422",
    "expires_in":3600,
    "scope":null,
    "refresh_token":"431238cd8d73b69512c6108e1b1e0c66"
}
 

可以看到服务器一并返回了refresh token。refresh_token用在access token过期后重新换取access token,省去用户重新授权。重新获取请求如下:

 

 

http://localhost/oauth/server/examples/mongo/token.php?

client_id=50001&

client_secret=pwd&

grant_type=refresh_token&

refresh_token=6cec87a92743accedae7bacd02f87049

 

需要在继承OAuth2类的数据库驱动类添加生成和获取refresh token的方法,示例代码如下:

 

  /**
   * Implements OAuth2::setRefreshToken().
   */
  protected function setRefreshToken($refresh_token, $client_id, $expires, $scope = NULL) {
    $this->db->refresh_tokens->insert(array(
      "_id" => $refresh_token,
      "client_id" => $client_id,
      "expires" => $expires,
      "scope" => $scope
    ));
    return;
  }
  
  /**
   * Implements OAuth2::getRefreshToken().
   */
  protected function getRefreshToken($refresh_token) {
    return $this->db->refresh_tokens->findOne(array("_id" => $refresh_token));
  }

 

换取access token成功后服务器会返回一个新的access token和refresh token

 

 

{
    "access_token":"3266e198e6c0ed9b1cdd8edb47ed499a",
    "expires_in":3600,
    "scope":null,
    "refresh_token":"38780eed063dd3765dd93719f915fdcf"
}
 

refresh token的有效期也可以在OAuth2的类里面调整,比access token有效期长很多。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics