qbnk/guzzle5-oauth2-subscriber

Guzzle 5.x 的 OAuth2 身份验证和重新授权 - 基于 nmrkt/guzzle5-oauth2-subscriber 衍生

v0.1.4 2015-05-05 12:41 UTC

This package is auto-updated.

Last update: 2024-09-21 23:53:07 UTC


README

从 NMRKT/guzzle5-oauth2-subscriber 衍生,并修复了一些错误

NMRKT 的实现似乎已被放弃,因为他们没有回复任何合并请求。然后我们决定发布我们的修复。

为 Guzzle 5.x 提供OAuth2 订阅者。

归属

此插件基于 Bojan Zivanovic 和 Damien Tournoud 的 Guzzle 3.x OAuth2 插件,来自 CommerceGuys guzzle-oauth2-plugin 存储库

我最初将该项目分支出来,但由于大部分代码已更改,我需要将版本重置为 < 1.0,所以我移动到了一个新的存储库。

功能

  • 通过支持的授权类型之一(代码、客户端凭据、用户凭据、刷新令牌)获取访问令牌。或者您也可以自己设置访问令牌。
  • 支持刷新令牌(存储它们并使用它们获取新的访问令牌)。
  • 处理令牌过期(获取新的令牌并重试失败的请求)。
  • 允许通过回调存储和查找访问令牌

用法

此插件扩展 Guzzle,透明地添加认证到出站请求,并在访问令牌不再有效时可选地尝试重新授权。

有几种授权类型可用,如 PasswordCredentialsClientCredentialsAuthorizationCode

访问令牌方法

如果您已经有了访问令牌,您可以使用它来对服务进行身份验证,但请注意,访问令牌旨在过期,获取新访问令牌的过程也包含在这个库中(例如,使用 PasswordCredentials 方法)。

以下是如何使用现有的访问令牌进行请求,因此不需要重新授权客户端

use kamermans\GuzzleOAuth2\OAuth2Subscriber;

// Setup OAuth
$oauth = new OAuth2Subscriber();

// Manually specify access_token.  When it expires, you will get an exception
$oauth->getTokenData()->accessToken = 'somelongtoken';

$client = new GuzzleHttp\Client();
// Attach OAuth subscriber to the Guzzle client and all URLs will be authenticated
$client->getEmitter()->attach($oauth);
$response = $client->get('http://somehost/some_secure_url');

echo "Status: ".$response->getStatusCode()."\n";

客户端凭据方法

客户端凭据通常用于服务器到服务器的身份验证。使用此授权类型时,客户端正在代表自己请求授权,因此只涉及两个实体。至少需要一个 client_idclient_secret,尽管许多服务还需要 scope 和其他参数。

以下是一个客户端凭据方法的示例

use kamermans\GuzzleOAuth2\GrantType\ClientCredentials;
use kamermans\GuzzleOAuth2\OAuth2Subscriber;

// Authorization client - this is used to request OAuth access tokens
$reauth_client = new GuzzleHttp\Client([
    // URL for access_token request
    'base_url' => 'http://some_host/access_token_request_url',
]);
$reauth_config = [
	"client_id" => "your client id",
	"client_secret" => "your client secret",
	"scope" => "your scope(s)", // optional
	"state" => time(), // optional
];
$grant_type = new ClientCredentials($reauth_client, $reauth_config);
$oauth = new OAuth2Subscriber($grant_type);

// This is the normal Guzzle client that you use in your application
$client = new GuzzleHttp\Client();
$client->getEmitter()->attach($oauth);
$response = $client->get('http://somehost/some_secure_url');

echo "Status: ".$response->getStatusCode()."\n";