Search by

augustdai / jyim-oauth2-php

augdai

PHP SDK for the Orion OAuth 2.0 / OpenID Connect public account platform (authorization code, PKCE, id_token verification)

v1.0.0 2026-12-01 03:34 UTC

This package is auto-updated.

Last update: 2026-12-01 03:45:06 UTC


README

Latest Stable Version Total Downloads PHP Version

对接 Orion 公众账号平台 的官方 PHP SDK。 封装授权码流程、PKCE、id_token 本地验签、令牌刷新轮换与撤销。

  • 零第三方依赖(只需 ext-curl / ext-json / ext-openssl)
  • 支持 PHP 8.1+
  • 机密客户端(有后端)与公共客户端(PKCE)同一套 API

安装

方式一:Packagist(已发布时)

composer require augustdai/jyim-oauth2-php

方式二:VCS 仓库(当前推荐)

在项目的 composer.json 里加仓库,然后安装:

{
    "repositories": [
        {
            "type": "vcs",
            "url": "git@github.com:augustdai/jyim-oauth2-php.git"
        }
    ],
    "require": {
        "augustdai/jyim-oauth2-php": "^1.0"
    }
}
composer update augustdai/jyim-oauth2-php

方式三:本地路径(联调/私有部署)

{
    "repositories": [
        { "type": "path", "url": "../oauth2-client-php" }
    ],
    "require": {
        "augustdai/jyim-oauth2-php": "*"
    }
}

发布到 Packagist 只需要:仓库公开 → 在 packagist.org 提交仓库地址。 之后 composer require 即可,版本按 git tag 走(git tag v1.0.0 && git push --tags)。

快速开始

use OrionJYIM\OAuth2Client\Client;
use OrionJYIM\OAuth2Client\Config;

$oauth = new Client(Config::fromArray([
    'issuer'        => 'https://oauth2.amin.wiki',
    'client_id'     => $_ENV['OAUTH_CLIENT_ID'],
    'client_secret' => $_ENV['OAUTH_CLIENT_SECRET'],   // 公共客户端留空
    'redirect_uri'  => 'https://your-site.com/auth/callback',
    'scopes'        => ['openid', 'profile', 'email'],
]));

// 1) 拉起授权
session_start();
header('Location: ' . $oauth->authorizationUrl());
exit;

// 2) 回调:校验 state → 换令牌
$token = $oauth->handleCallback($_GET);   // 用户点「取消」会抛异常,见下方

// 3) 验 id_token(本地 RS256 验签 + iss/aud/exp/nonce 校验)
$claims = $oauth->verifyIdToken($token->idToken, null, $token->accessToken);

// 4) 取用户信息
$userinfo = $oauth->userinfo($token->accessToken);

// 5) 用 sub 建号(不要用 email)
$identity = find_or_create_identity($claims['sub']);

核心 API

Config::fromArray(array $options)

参数 必填 说明
issuer ✅ 授权服务器地址,如 https://oauth2.amin.wiki
client_id ✅ 应用 ID
client_secret 公共客户端留空 留空即启用 PKCE 模式
redirect_uri ✅ 必须与平台登记的完全一致
scopes 默认 ['openid','profile']
clock_skew 校验时钟偏移容忍,默认 60 秒

authorizationUrl(array $options = [])

生成授权地址,并自动把 state / nonce / PKCE verifier 存进 StateStore。

可选:scopes、state、nonce、prompt(login/consent/none)、login_hint。

handleCallback(?array $query = null)

校验 state(一次性,用完即删)→ 用 code 换令牌,返回 TokenSet。

  • 缺少/错误 state:抛 OAuthClientException
  • 用户拒绝授权:抛 OAuthServerException,用 isAccessDenied() 判断

TokenSet

成员 说明
accessToken 不透明令牌,2 小时
refreshToken 刷新令牌,30 天,每次刷新都会变
idToken JWT,可本地验签
expiresIn / expiresAt() / isExpired($skew = 60) 有效期
scopes() 已授权 scope
toArray() / fromStorage() 持久化与还原

refresh(string $refreshToken)

平台启用了刷新轮换:返回值里的 refreshToken 是新的, 必须立刻覆盖保存;继续用旧值会让整条令牌链被撤销。

userinfo(string $accessToken)

返回 sub / preferred_username / name / picture / email / phone_number, 只包含已授权 scope 覆盖的字段。401 抛 OAuthServerException。

verifyIdToken(string $idToken, ?string $nonce = null, ?string $accessToken = null)

本地校验,任一项失败抛 VerificationException:

  1. alg 必须 RS256(拒绝 none)
  2. 按 kid 从 JWKS 取公钥验签(密钥轮换时自动重新拉取)
  3. iss 等于配置的 issuer
  4. aud 包含自己的 client_id(多受众时校验 azp)
  5. exp / nbf / iat 在容忍范围内
  6. nonce 与本次授权生成的 nonce 一致
  7. 传了 accessToken 时校验 at_hash

revoke(string $token, string $hint = '')

撤销 access 或 refresh token,联动失效对端。

状态存储

state、PKCE verifier、nonce 需要跨请求保存。默认用 PHP session:

new Client($config);                                   // SessionStateStore(需 session_start)
new Client($config, new ArrayStateStore());            // CLI / 测试
new Client($config, new MyRedisStateStore());          // 自行实现 StateStoreInterface

自定义只需实现两个方法:

interface StateStoreInterface
{
    public function put(string $state, array $payload): void;
    public function pull(string $state): ?array;   // 取出并删除
}

自定义 HTTP 传输

项目里已有 Guzzle / PSR-18 时,实现 HttpClientInterface 传入即可:

$oauth = new Client($config, null, new MyGuzzleClient());

签名:request(string $method, string $url, array $headers = [], ?string $body = null): HttpResponse

错误处理

异常 场景
OAuthClientException 本地问题:配置错误、state 校验失败、网络异常
OAuthServerException 服务端按 RFC 6749 返回的 error;getError() 取错误码
VerificationException id_token 校验失败(必须视为不可信)
use OrionJYIM\OAuth2Client\Exception\OAuthServerException;
use OrionJYIM\OAuth2Client\Exception\VerificationException;

try {
    $token = $oauth->handleCallback($_GET);
} catch (OAuthServerException $e) {
    if ($e->isAccessDenied()) {
        // 用户点了取消,属于正常分支
        redirect('/?notice=cancelled');
    }
    // invalid_grant / invalid_client ...
    error_log($e->getError() . ': ' . $e->getDescription());
}

框架集成

Laravel

// config/services.php
'oauth' => [
    'client_id'     => env('OAUTH_CLIENT_ID'),
    'client_secret' => env('OAUTH_CLIENT_SECRET'),
    'redirect'      => env('OAUTH_REDIRECT_URI'),
],

// 控制器
public function redirect()
{
    $oauth = app(OAuthClient::class);
    return redirect($oauth->authorizationUrl());
}

StateStore 用 Laravel session 实现即可(Session::put/pull)。

Hyperf

#[Inject]
protected OAuthClient $oauth;   // 在 dependencies.php 里注册为单例

public function callback(): ResponseInterface
{
    $token = $this->oauth->handleCallback($this->request->all());
    $claims = $this->oauth->verifyIdToken($token->idToken, null, $token->accessToken);

    return $this->response->json(['sub' => $claims['sub']]);
}

StateStore 建议用 Redis 实现(协程环境下 $_SESSION 不可用)。

测试

# 需要本地或测试环境的 IdP 在跑
php tests/integration.php

# 指定环境
IDP_BASE=https://oauth2.amin.wiki IDP_USER=demo IDP_PASS=xxx php tests/integration.php

覆盖 35 项断言:授权地址生成、登录跳转、code 换令牌、id_token 验签 (含篡改签名/错误 aud 的负向用例)、userinfo、刷新轮换、旧 refresh 重放整链撤销、 撤销后 401、PKCE 挑战值计算。

安全须知

  • client_secret 只放服务端,绝不进前端、App 包、代码仓库
  • state 必须校验,否则可被 CSRF
  • 公共客户端(SPA/App)必须 PKCE,且平台侧会强制要求
  • sub 才是稳定用户标识;email、username 都可能被用户改
  • 验签失败一律拒绝,不要「降级信任」payload 内容

完整协议说明见 平台开发文档。