客户端凭证
此授权适用于机器对机器身份验证,例如用于通过 API 执行维护任务的 cron 作业。另一个示例是客户端向不需要用户许可的 API 发出请求。
步骤
客户端向授权服务器发送具有以下正文参数的 POST 请求:
- grant_type 值为 client_credentials
- client_id 客户端 ID
- client_secret 客户端密钥
- scope 具有以空格分隔的已请求范围权限列表。
授权服务器将使用包含以下属性的 JSON 对象进行响应:
- token_type 值为 Bearer
- expires_in 使用表示访问令牌的 TTL (整数)
- access_token 使用授权服务器的私钥签名的 JWT
设置
无论在何处初始化对象,请初始化授权服务器的新实例并绑定存储接口和授权代码授予:
// Init our repositories
$clientRepository = new ClientRepository(); // instance of ClientRepositoryInterface
$scopeRepository = new ScopeRepository(); // instance of ScopeRepositoryInterface
$accessTokenRepository = new AccessTokenRepository(); // instance of AccessTokenRepositoryInterface
// 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
);
// Enable the client credentials grant on the server
$server->enableGrantType(
new \League\OAuth2\Server\Grant\ClientCredentialsGrant(),
new \DateInterval('PT1H') // access tokens will expire after 1 hour
);实现
请注意:此处的这些示例演示了 Slim 框架的用法;Slim不是使用此库的必要条件,您只需要生成与PSR7兼容的HTTP请求和响应的东西。
客户端将请求访问令牌,因此请创建 /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 {
// Try to respond to the request
return $server->respondToAccessTokenRequest($request, $response);
} catch (\League\OAuth2\Server\Exception\OAuthServerException $exception) {
// All instances of OAuthServerException can be formatted into a HTTP response
return $exception->generateHttpResponse($response);
} catch (\Exception $exception) {
// Unknown exception
$body = new Stream('php://temp', 'r+');
$body->write($exception->getMessage());
return $response->withStatus(500)->withBody($body);
}
});过期
token 过期后,需要重新发起上述步骤。