serendipity_hq/oauth-guzzle-middleware

0.1.0 2016-02-17 15:35 UTC

This package is auto-updated.

Last update: 2024-09-05 04:46:31 UTC


README

Latest Stable Version Build Status Total Downloads License Code Climate Test Coverage Issue Count StyleCI SensioLabsInsight Dependency Status

Guzzle 6+ OAuth 中间件

使用 OAuth 签名 HTTP 请求。

本版本仅适用于 Guzzle 6.0 及以上版本!

(从 https://github.com/guzzle/oauth-subscriber 分支,并将其从原始仓库中分离出来,以便能够使用持续集成服务器和其他分析工具)。

安装

需要 PHP OAuth 扩展

可以使用 Composer 安装此项目。将以下内容添加到您的 composer.json

{
    "require": {
        "serendipity_hq/oauth-guzzle-middleware": "~0.1"
    }
}

关于 OAuth

来自 OAuth Core 1.0a

OAuth 协议允许网站或应用程序(消费者)通过 API 从 Web 服务(服务提供商)访问受保护资源,而无需用户向消费者披露他们的服务提供商凭据。更普遍地说,OAuth 创建了一种可自由实现的通用 API 认证方法。

一个示例用例是允许打印服务 printer.example.com(消费者)访问存储在 photos.example.net(服务提供商)上的私人照片,而无需用户向 printer.example.com 提供他们的 photos.example.net 凭据。

OAuth 不需要特定的用户界面或交互模式,也不指定服务提供商如何验证用户,这使得该协议非常适合认证凭据不可用给消费者的情况,如 OpenID。

OAuth 的目标是统一委托 Web 服务认证的体验和实现,将其纳入单一、社区驱动的协议。OAuth 建立在由各种网站独立实现的现有协议和最佳实践之上。一个开放标准,无论是大提供商还是小提供商都支持,为应用程序开发者和这些应用程序的用户提供一致且值得信赖的体验。

OAuth 版本

  • [2007] OAuth Core 1.0 ([已弃用] 社区 - OAuth.net)
  • [2009] OAuth Core 1.0a (社区 - OAuth.net)
  • [2010] OAuth 协议 1.0 (信息性 - RFC5849)
  • [2012] OAuth 协议 2.0 (标准 - RFC6749)

此库支持

  • OAuth Core 1.0a
  • OAuth 协议 1.0 (待实现)
  • OAuth 协议 2.0 (待实现)

如何使用 OAuth Core 1.0a 中间件

您可以通过传递或不传递 tokentoken_secret 值到 OAuth* 中间件来发送双端和三端 Requests

有关多端请求的更多信息,请参阅 hueniverse.com 上的术语段落

有关完整示例,请参阅 Twitter 示例

发送三端 Request

/**
 * Sends ALL THE REQUESTS authenticated with OAuth.
 * @see [docs/examples/Twitter/](docs/examples/Twitter/) for more details.
 */

use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware\OpenAuthentication\OAuth10a;
use GuzzleHttp\RequestOptions;

// Consumer Credentials: created at Precondition 2
$consumerKey    = 'your-consumer-key';
$consumerSecret = 'your-consumer-secret';

// Set here the access token generated at Precondition 3
$accessTokenKey    = 'your-token-key';
$accessTokenSecret = 'your-token-secret';

// The home_timeline endpoint
$resourceUrl = 'statuses/home_timeline.json';

try {
    // Instantiate the Guzzle Client and the OAuth10a middleware
    $handler = new CurlHandler();
    $stack = HandlerStack::create($handler);
    $middleware = new OAuth10a([
        'consumer_key'     => $consumerKey,
        'consumer_secret'  => $consumerSecret,
        'token'            => $accessTokenKey,
        'token_secret'     => $accessTokenSecret,
        'request_method'   => OAuth10a::REQUEST_METHOD_HEADER,
        'signature_method' => OAuth10a::SIGNATURE_METHOD_HMAC,
    ]);
    $stack->push($middleware);

    // Set the client params
    $clientParams = [
        'base_uri'                      => 'https://api.twitter.com/1.1/',
        'handler'                       => $stack,
        // Set the oauth authentication for ALL REQUESTS
        RequestOptions::AUTH            => 'oauth',
        RequestOptions::HTTP_ERRORS     => false,
        RequestOptions::DEBUG           => true,
        RequestOptions::ALLOW_REDIRECTS => ['track_redirects' => true]
    ];

    $guzzleClient = new Client($clientParams);

    $tweetsList = $guzzleClient->get($resourceUrl);
    dump(json_decode($tweetsList->getBody()->__toString(), true));
} catch (\Exception $e) {
    dump($e->getMessage());
    echo "<br/>";
    dump($e);
}

要仅使用OAuth中间件对单个Request进行认证,请从$clientParams数组中移除RequestOptions::AUTH => 'oauth'选项,并将其放入$requestParams数组中

/**
 * @see [docs/examples/Twitter/](docs/examples/Twitter/) for more details.
 */

...

try {
    ...
    $stack->push($middleware);

    // Set the client params
    $clientParams = [
        'base_uri'                      => 'https://api.twitter.com/1.1/',
        'handler'                       => $stack,
        // Remove the option from the CLient parameters
        // RequestOptions::AUTH            => 'oauth',
        RequestOptions::HTTP_ERRORS     => false,
        RequestOptions::DEBUG           => true,
        RequestOptions::ALLOW_REDIRECTS => ['track_redirects' => true]
    ];

    $guzzleClient = new Client($clientParams);

    $requestParams = [
        RequestOptions::AUTH => 'oauth'
    ];

    // Use OAuth on a pre Request basis
    $tweetsList = $guzzleClient->get($resourceUrl, $requestParams);

    dump(json_decode($tweetsList->getBody()->__toString(), true));
} catch (\Exception $e) {
    dump($e->getMessage());
    echo "<br/>";
    dump($e);
}

发送双端Request

要发送双端Requests,只需省略tokentoken_secret参数。

/**
 * Sends ALL THE REQUESTS authenticated with OAuth.
 * @see [docs/examples/Twitter/](docs/examples/Twitter/) for more details.
 */

use GuzzleHttp\Client;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Middleware\OpenAuthentication\OAuth10a;
use GuzzleHttp\RequestOptions;

// Consumer Credentials: created at Precondition 2
$consumerKey    = 'your-consumer-key';
$consumerSecret = 'your-consumer-secret';

// DO NOT SET THOSE PARAMETERS
// $accessTokenKey    = 'your-token-key';
// $accessTokenSecret = 'your-token-secret';

// The home_timeline endpoint
$resourceUrl = 'statuses/home_timeline.json';

try {
    // Instantiate the Guzzle Client and the OAuth10a middleware
    $handler = new CurlHandler();
    $stack = HandlerStack::create($handler);
    $middleware = new OAuth10a([
        'consumer_key'     => $consumerKey,
        'consumer_secret'  => $consumerSecret,
        // DO NOT SET THOSE PARAMETERS
        // 'token'            => $accessTokenKey,
        // 'token_secret'     => $accessTokenSecret,
        'request_method'   => OAuth10a::REQUEST_METHOD_HEADER,
        'signature_method' => OAuth10a::SIGNATURE_METHOD_HMAC,
    ]);
    $stack->push($middleware);

    // Set the client params
    $clientParams = [
        'base_uri'                      => 'https://api.twitter.com/1.1/',
        'handler'                       => $stack,
        // Set the oauth authentication for ALL REQUESTS
        RequestOptions::AUTH            => 'oauth',
        RequestOptions::HTTP_ERRORS     => false,
        RequestOptions::DEBUG           => true,
        RequestOptions::ALLOW_REDIRECTS => ['track_redirects' => true]
    ];

    $guzzleClient = new Client($clientParams);

    $tweetsList = $guzzleClient->get($resourceUrl);
    dump(json_decode($tweetsList->getBody()->__toString(), true));
} catch (\Exception $e) {
    dump($e->getMessage());
    echo "<br/>";
    dump($e);
}

使用RSA-SH1签名方法

    use GuzzleHttp\Middleware\OpenAuthentication\Oauth10a;

    $stack = HandlerStack::create();

    $middleware = new Oauth10a([
        'consumer_key'           => 'my_key',
        'consumer_secret'        => 'my_secret',
        'private_key_file'       => 'my_path_to_private_key_file',
        'private_key_passphrase' => 'my_passphrase',
        'signature_method'       => Oauth10a::SIGNATURE_METHOD_RSA,
    ]);
    $stack->push($middleware);

    $client = new Client([
        'handler' => $stack
    ]);

    $response = $client->get('http://httpbin.org', ['auth' => 'oauth']);