Google oAuth2 JWT 生成器

dev-master 2015-04-05 02:01 UTC

This package is not auto-updated.

Last update: 2024-10-02 08:18:02 UTC


README

Google® oAuth2 JWT 生成器类

介绍

这个类已经连接到另一个专有远程 REST 抽象,但我打算利用这个类在我的 Adapter 项目中实现 Google oAuth2 服务帐户身份验证方法。

目前,您可能能够将其集成到自己的远程 REST 抽象中。

这正是它的目的;对于那些认为 PHP Google 客户端库过于臃肿,但又难以弄清楚如何在避免难以理解的 bad_request / invalid_grant 响应的同时生成 JWT / 谈判令牌的人来说。

生成 JWT

提供一个配置数组,如下所示

$jwtConfig = [
  'key'    => [
    'pass'  => 'notasecret',
    // Converted from the .p12 off of the Developer console
    'path'  => 'file://' . storage_path() . '/certs/google.pem'
  ],
  'header'  => [
    'alg'  => 'RS256',
    'typ'  => 'JWT'
  ],
  'claim_set' => [
    'iss'     => '',  // service account e-mail
    'scope'   => 'https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/prediction',
    'aud'     => 'https://www.googleapis.com/oauth2/v3/token',
    'exp'     => '+30 minutes',
    'sub'     => ''
  ]
];

$generator = new Generator($jwtConfig);

$returnedJwt = $generator->generate();

确保已启用相关 API,并且用户具有读写访问权限。

谈判获取访问令牌

JWT 可以通过以下伪代码来谈判访问令牌

POST https://www.googleapis.com/oauth2/v3/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=urlencode(JWT::$grant_type)&assertion=urlencode($returnedJwt)

在 Google oAuth2 的情况下,grant_type 几乎总是 urn:ietf:params:oauth:grant-type:jwt-bearer

如果出现问题

该类旨在通过将您的时钟转换为 UTC 来防止难以理解的 bad_request,但始终确保您的系统时钟与 NTP 保持同步,并且您使用服务帐户电子邮件地址(而不是您的 ID)。

如果一切顺利...

如果一切顺利,您将得到如下内容,您可以将其缓存以供进一步使用

{
  "access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
  "token_type" : "Bearer",
  "expires_in" : 3600
}

访问令牌过期后,您只需重新构建 JWT 并请求新的访问令牌即可。

使用访问令牌进行身份验证

将此标头放在每个 Google API 请求上

GET https://www.googleapis.com/calendar/v3/users/me/calendarlist HTTP/1.1
Authorization: Bearer 1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M