OAuth2.0在PHP中需按角色选型实现:多数项目仅需Client角色,用league/oauth2-client时须手动处理token持久化、未授权拦截和scope校验;自建Authorization Server应选用oauth2-server库,严格配置密钥路径与grant type;跨域、CSRF防护及HTTPS为强制安全要求。
PHP 本身不内置 OAuth2 协议支持,所谓“集成”,本质是选对角色(Resource Owner / Client / Authorization Server / Resource Server),再按角色职责选用或实现对应组件。多数项目只需作为 OAuth2 Client(比如用 PHP 后端代用户去请求微信/钉钉/GitHub 的 API),极少数需自建 Authorization Server(如统一认证中心)。直接装个 league/oauth2-client 就开跑,常在重定向、token 刷新、scope 校验上出问题。
这个库只管协议流程,不自动持久化 token、不拦截未授权请求、不校验 scope 是否被授予。漏掉任意一项,上线后就会出现“用户登着登着 401 了”或“能调接口但拿不到邮箱字段”。
$_SESSION(短生命周期)或数据库+加密字段(长周期,需配 refresh_token)expires:库返回的 $token->getExpires() 是时间戳,过期得主动调 $provider->getAccessToken('refresh_token', [...])
scope=openid,unionid,但你代码里只用了 openid,没问题;若你代码依赖 email 但响应里没这个 scope,就得引导用户重新授权并显式传 scope=email
php-oauth 扩展早已废弃(PHP 7.4+ 移除),且只支持 OAuth1。真要自建授权服务器,得用成熟方案:oauth2-server(by The PHP League)是当前最稳的选择,它把 RFC6749 的四种 grant type 全部拆成可插拔对象。
use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
$server = new AuthorizationServer(
$clientRepository,
$accessTokenRepository,
$scopeRepository,
new \League\OAuth2\Server\CryptKey('file://path/to/private.key'),
new \League\OAuth2\Server\CryptKey('file://path/to/public.key')
);
// 必须显式添加 grant type,否则 /token 接口直接 404
$server->enableGrantType(
new \League\OAuth2\Server\Grant\ClientCredentialsGrant(),
new \DateInterval('PT1H') // a
ccess_token 有效期
);
注意:密钥路径必须是 file:// 开头的绝对路径,相对路径会静默失败;ClientCredentialsGrant 和 AuthorizationCodeGrant 的存储要求不同——后者强制需要 AuthCodeRepository,漏实现就会抛 LogicException。
OAuth2 流程天然涉及多次跳转和敏感凭证传递,开发环境容易忽略基础安全约束:
https://a.com/callback ≠ https://a.com/callback/,末尾斜杠都算不一致;本地调试建议用 http://localhost:8000/callback,别用 127.0.0.1
$_SESSION['oauth_state'],回调时比对,不一致立刻终止code
state 参数生成别用 rand(),得用 bin2hex(random_bytes(16));code 一次有效,用完立即失效,别手贱在日志里全量打印。