league/oauth2-google
Composer 安装命令:
composer require league/oauth2-google
包简介
Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client
README 文档
README
This package provides Google OAuth 2.0 support for the PHP League's OAuth 2.0 Client.
This package is compliant with PSR-1, PSR-2 and PSR-4. If you notice compliance oversights, please send a patch via pull request.
Requirements
The following versions of PHP are supported. Support for older PHP versions is available in version 4.2 (and older) of this library.
- PHP 8.0
- PHP 8.1
- PHP 8.2
- PHP 8.3
- PHP 8.4
- PHP 8.5
This package uses OpenID Connect to authenticate users with Google accounts.
To use this package, it will be necessary to have a Google client ID and client
secret. These are referred to as {google-client-id} and {google-client-secret}
in the documentation.
Please follow the Google instructions to create the required credentials.
Installation
To install, use composer:
composer require league/oauth2-google
Usage
Authorization Code Flow
require __DIR__ . '/vendor/autoload.php'; use League\OAuth2\Client\Provider\Google; session_start(); // Remove if session.auto_start=1 in php.ini $provider = new Google([ 'clientId' => '{google-client-id}', 'clientSecret' => '{google-client-secret}', 'redirectUri' => 'https://example.com/callback-url', 'hostedDomain' => 'example.com', // optional; used to restrict access to users on your G Suite/Google Apps for Business accounts ]); if (!empty($_GET['error'])) { // Got an error, probably user denied access exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8')); } elseif (empty($_GET['code'])) { // If we don't have an authorization code then get one $authUrl = $provider->getAuthorizationUrl(); $_SESSION['oauth2state'] = $provider->getState(); header('Location: ' . $authUrl); exit; } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { // State is invalid, possible CSRF attack in progress unset($_SESSION['oauth2state']); exit('Invalid state'); } else { // Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // Optional: Now you have a token you can look up a users profile data try { // We got an access token, let's now get the owner details $ownerDetails = $provider->getResourceOwner($token); // Use these details to create a new profile printf('Hello %s!', $ownerDetails->getFirstName()); } catch (Exception $e) { // Failed to get user details exit('Something went wrong: ' . $e->getMessage()); } // Use this to interact with an API on the users behalf echo $token->getToken(); // Use this to get a new access token if the old one expires echo $token->getRefreshToken(); // Unix timestamp at which the access token expires echo $token->getExpires(); }
Available Options
The Google provider has the following options:
accessTypeto use online or offline accesshostedDomainto authenticate G Suite userspromptto modify the prompt that the user will seescopesto request access to additional user information
Accessing Token JWT
Google provides a JSON Web Token (JWT) with all access tokens. This token
contains basic information about the authenticated user. The JWT
can be accessed from the id_token value of the access token:
/** @var League\OAuth2\Client\Token\AccessToken $token */ $values = $token->getValues(); /** @var string */ $jwt = $values['id_token'];
Parsing the JWT will require a JWT parser. Refer to parser documentation for instructions.
Refreshing a Token
Refresh tokens are only provided to applications which request offline access. You can specify offline access by setting the accessType option in your provider:
use League\OAuth2\Client\Provider\Google; $provider = new Google([ 'clientId' => '{google-client-id}', 'clientSecret' => '{google-client-secret}', 'redirectUri' => 'https://example.com/callback-url', 'accessType' => 'offline', ]);
It is important to note that the refresh token is only returned on the first request after this it will be null. You should securely store the refresh token when it is returned:
$token = $provider->getAccessToken('authorization_code', [ 'code' => $code ]); // persist the token in a database $refreshToken = $token->getRefreshToken();
If you ever need to get a new refresh token you can request one by forcing the consent prompt:
$authUrl = $provider->getAuthorizationUrl(['prompt' => 'consent', 'access_type' => 'offline']);
Now you have everything you need to refresh an access token using a refresh token:
use League\OAuth2\Client\Provider\Google; use League\OAuth2\Client\Grant\RefreshToken; $provider = new Google([ 'clientId' => '{google-client-id}', 'clientSecret' => '{google-client-secret}', 'redirectUri' => 'https://example.com/callback-url', ]); $grant = new RefreshToken(); $token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
Scopes
Additional scopes can be set by using the scope parameter when
generating the authorization URL:
$authorizationUrl = $provider->getAuthorizationUrl([ 'scope' => [ 'scope-url-here' ], ]);
Testing
Tests can be run with:
composer test
Style checks can be run with:
composer check
Contributing
Please see CONTRIBUTING for details.
Credits
License
The MIT License (MIT). Please see License File for more information.
league/oauth2-google 适用场景与选型建议
league/oauth2-google 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 23.17M 次下载、GitHub Stars 达 422, 最近一次更新时间为 2015 年 03 月 22 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「authorization」 「Authentication」 「client」 「oauth」 「oauth2」 「google」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 league/oauth2-google 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 league/oauth2-google 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 league/oauth2-google 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Ory-Hydra OAuth 2.0 Client Provider for The PHP League OAuth2-Client
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
Mock PSR-18 HTTP client
统计信息
- 总下载量: 23.17M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 457
- 点击次数: 22
- 依赖项目数: 133
- 推荐数: 37
其他信息
- 授权协议: MIT
- 更新时间: 2015-03-22