使用刷新令牌

时间:2015-05-08 09:46:04

标签: php oauth-2.0

我目前正在使用 thephpleague / oauth2 库实施OAuth2。我已经添加了刷新令牌授权,并且访问令牌响应已经包含刷新令牌。但是,我不知道如何使用该刷新令牌来获取新的访问令牌。

我检查了文档,但我没有看到任何相关内容。 oauth2-client库有它的方法,但我不打算使用它。

我的刷新令牌授权代码:

$server->setRefreshTokenStorage(new RefreshTokenStorage);

$refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
$authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();

$server->addGrantType($authCodeGrant);
$server->addGrantType($refreshTokenGrant);
$response = $server->issueAccessToken();

我的问题是如何使用刷新令牌测试,我可以检索新的访问令牌?我是否必须实现与授权代码授权使用的新端点不同的新端点?

这是获取令牌的代码。有什么意见吗?

public function actionToken(){

    $authCodeModel = new \app\models\OAuth_Auth_Codes;

    if(!isset($_POST['code'])){
        throw new \yii\web\HttpException(400,"Required parameter \'code\' is missing or invalid.");
    }

    $result = $authCodeModel->find()->where(['authorization_code' => trim($_POST['code'])])->one();

    if(!empty($result)){

        $user_id = $result->user_id;

        $session2 = new Session();
        $session2->open();

        $server = new AuthorizationServer;
        $server->setSessionStorage(new SessionStorage);
        $server->setAccessTokenStorage(new AccessTokenStorage);
        $server->setClientStorage(new ClientStorage);
        $server->setScopeStorage(new ScopeStorage);
        $server->setAuthCodeStorage(new AuthCodeStorage);
        $server->setRefreshTokenStorage(new RefreshTokenStorage);

        $refreshTokenGrant = new \League\OAuth2\Server\Grant\RefreshTokenGrant();
        $authCodeGrant = new \League\OAuth2\Server\Grant\AuthCodeGrant();

        $server->addGrantType($authCodeGrant);
        $server->addGrantType($refreshTokenGrant);

        $response = $server->issueAccessToken();

        $model = new \app\models\OAuth_Access_Tokens();
        $accessTokenModel = $model->find()->where(['access_token' => $response['access_token']])->one();
        $accessTokenModel->setAttribute('user_id',''.$user_id);
        $accessTokenModel->save(FALSE);

        return json_encode($response);
    }
    else{
        throw new \yii\web\UnauthorizedHttpException("You have provided an invalid authorization code.");
    }
}

1 个答案:

答案 0 :(得分:2)

在PHP中使用cURL支持:

$postData = array(
    "grant_type" => "refresh_token",
    "client_id" => $clientID,
    "client_secret" => $clientSecret,
    "refresh_token" => $refreshToken
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $tokenEndpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
$response = curl_exec($ch);
curl_close($ch);
$r = json_decode($response);
echo $r->access_token;

编辑: 有关服务器端示例,请参阅:https://github.com/thephpleague/oauth2-server/blob/master/tests/unit/Grant/RefreshTokenGrantTest.php,例如:

$server = new AuthorizationServer();
$grant = new RefreshTokenGrant();
$server->addGrantType($grant);
$server->issueAccessToken();