访问令牌最终会过期;但是,某些授权使用刷新令牌进行响应,使客户端能够刷新访问令牌。
步骤
客户端向授权服务器发送具有以下正文参数的 POST 请求:
- grant_type 授权类型,值为 refresh_token
- refresh_token 刷新令牌值
- client_id 客户端 ID
- client_secret 客户端密钥
- scope 具有以空格分隔的已请求范围权限列表。这是可选的;如果未发送,将使用原始作用域,否则可以请求一组缩小的作用域。
授权服务器将使用包含以下属性的 JSON 对象进行响应:
- token_type 与值 Bearer
- expires_in 使用表示访问令牌的 TTL (整数)
- access_token 使用授权服务器的私钥签名的新 JWT
- refresh_token 可用于在访问令牌过期时刷新访问令牌
设置
无论在何处初始化对象,请初始化授权服务器的新实例并绑定存储接口和授权代码授予:
// Init our repositories
$clientRepository = new ClientRepository();
$accessTokenRepository = new AccessTokenRepository();
$scopeRepository = new ScopeRepository();
$refreshTokenRepository = new RefreshTokenRepository();
// Path to public and private keys
$privateKey = 'file://path/to/private.key';
//$privateKey = new CryptKey('file://path/to/private.key', 'passphrase'); // if private key has a pass phrase
$encryptionKey = 'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'; // generate using base64_encode(random_bytes(32))
// Setup the authorization server
$server = new \League\OAuth2\Server\AuthorizationServer(
$clientRepository,
$accessTokenRepository,
$scopeRepository,
$privateKey,
$encryptionKey
);
$grant = new \League\OAuth2\Server\Grant\RefreshTokenGrant($refreshTokenRepository);
$grant->setRefreshTokenTTL(new \DateInterval('P1M')); // new refresh tokens will expire after 1 month
// Enable the refresh token grant on the server
$server->enableGrantType(
$grant,
new \DateInterval('PT1H') // new access tokens will expire after an hour
);实现
客户端将请求访问令牌,因此请创建 /access_token。
$app->post('/access_token', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
/* @var \League\OAuth2\Server\AuthorizationServer $server */
$server = $app->getContainer()->get(AuthorizationServer::class);
// Try to respond to the request
try {
return $server->respondToAccessTokenRequest($request, $response);
} catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
});