forked from laysense/laysite
145 lines
7.1 KiB
PHP
145 lines
7.1 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Content;
|
|
|
|
use Firebase\JWT\JWK;
|
|
use Firebase\JWT\JWT;
|
|
use GuzzleHttp\Client;
|
|
use GuzzleHttp\Psr7\Utils;
|
|
use League\OAuth2\Client\OptionProvider\HttpBasicAuthOptionProvider;
|
|
use League\OAuth2\Client\OptionProvider\PostAuthOptionProvider;
|
|
use League\OAuth2\Client\Provider\GenericProvider;
|
|
use RuntimeException;
|
|
|
|
final class IdentityProvider
|
|
{
|
|
public readonly GenericProvider $client;
|
|
private readonly Client $http;
|
|
private array $oidc = [];
|
|
|
|
public function __construct(private readonly array $config, string $secret)
|
|
{
|
|
$this->http = new Client(['timeout' => 8, 'connect_timeout' => 4, 'allow_redirects' => false]);
|
|
$scope = preg_split('/\s+/', trim($config['scope']), -1, PREG_SPLIT_NO_EMPTY);
|
|
$authorization = $config['authorization'];
|
|
$token = $config['token'];
|
|
$userinfo = $config['userinfo'];
|
|
if ($config['mode'] === 'oidc') {
|
|
$this->oidc = $this->document(rtrim($config['issuer'], '/') . '/.well-known/openid-configuration');
|
|
if (($this->oidc['issuer'] ?? null) !== $config['issuer']) {
|
|
throw new RuntimeException('OIDC Issuer 与发现文档不一致。');
|
|
}
|
|
$authorization = $this->endpoint($this->oidc['authorization_endpoint'] ?? '');
|
|
$token = $this->endpoint($this->oidc['token_endpoint'] ?? '');
|
|
$userinfo = isset($this->oidc['userinfo_endpoint']) ? $this->endpoint($this->oidc['userinfo_endpoint']) : '';
|
|
$scope = array_values(array_unique(['openid', 'profile', 'email', ...$scope]));
|
|
}
|
|
$auth = $config['token_auth'];
|
|
if ($auth === '') {
|
|
$supported = $this->oidc['token_endpoint_auth_methods_supported'] ?? ['client_secret_basic'];
|
|
if ($this->oidc === [] || (!in_array('client_secret_basic', $supported, true) && in_array('client_secret_post', $supported, true))) {
|
|
$auth = 'client_secret_post';
|
|
} elseif (in_array('client_secret_basic', $supported, true)) {
|
|
$auth = 'client_secret_basic';
|
|
} else {
|
|
throw new RuntimeException('身份服务没有公布受支持的令牌端点认证方式。');
|
|
}
|
|
}
|
|
$this->client = new GenericProvider([
|
|
'clientId' => $config['client_id'], 'clientSecret' => $secret,
|
|
'redirectUri' => View::absolute('/account/callback'), 'urlAuthorize' => $authorization,
|
|
'urlAccessToken' => $token, 'urlResourceOwnerDetails' => $userinfo,
|
|
'pkceMethod' => GenericProvider::PKCE_METHOD_S256, 'scopes' => $scope, 'scopeSeparator' => ' ',
|
|
], [
|
|
'httpClient' => $this->http,
|
|
'optionProvider' => $auth === 'client_secret_basic' ? new HttpBasicAuthOptionProvider() : new PostAuthOptionProvider(),
|
|
]);
|
|
}
|
|
|
|
public function authorization(string $nonce): string
|
|
{
|
|
return $this->client->getAuthorizationUrl($this->oidc === [] ? [] : ['nonce' => $nonce]);
|
|
}
|
|
|
|
public function profile(string $code, string $proof, string $nonce): array
|
|
{
|
|
$this->client->setPkceCode($proof);
|
|
$token = $this->client->getAccessToken('authorization_code', ['code' => $code]);
|
|
if ($this->oidc === []) {
|
|
$claims = $this->client->getResourceOwner($token)->toArray();
|
|
} else {
|
|
$claims = $this->verifiedClaims($token->getValues()['id_token'] ?? '', $nonce);
|
|
if (isset($this->oidc['userinfo_endpoint'])) {
|
|
$more = $this->client->getResourceOwner($token)->toArray();
|
|
if (($more['sub'] ?? null) !== $claims['sub']) {
|
|
throw new RuntimeException('OIDC 用户资料的主体与 ID Token 不一致。');
|
|
}
|
|
$claims = $more + $claims;
|
|
}
|
|
}
|
|
$subject = $claims[$this->oidc !== [] ? 'sub' : $this->config['subject_field']] ?? null;
|
|
if ((!is_string($subject) && !is_int($subject)) || (string) $subject === '' || strlen((string) $subject) > 255) {
|
|
throw new RuntimeException('身份服务没有返回有效的用户标识。');
|
|
}
|
|
$name = $claims[$this->config['name_field'] ?: 'name'] ?? $claims['preferred_username'] ?? (string) $subject;
|
|
$avatar = $claims[$this->config['avatar_field'] ?: 'picture'] ?? '';
|
|
return [
|
|
'subject' => (string) $subject,
|
|
'name' => is_string($name) ? mb_substr($name, 0, 100) : (string) $subject,
|
|
'avatar' => is_string($avatar) && strlen($avatar) <= 2048 && str_starts_with($avatar, 'https://') && Html::url($avatar, true) ? $avatar : '',
|
|
];
|
|
}
|
|
|
|
private function verifiedClaims(mixed $encoded, string $nonce): array
|
|
{
|
|
if (!is_string($encoded) || strlen($encoded) > 16384 || substr_count($encoded, '.') !== 2) {
|
|
throw new RuntimeException('身份服务没有返回有效的 ID Token。');
|
|
}
|
|
$header = JWT::jsonDecode(JWT::urlsafeB64Decode(explode('.', $encoded, 2)[0]));
|
|
$algorithm = $header->alg ?? '';
|
|
if (!in_array($algorithm, ['RS256', 'RS384', 'RS512', 'ES256', 'ES384'], true)) {
|
|
throw new RuntimeException('身份服务使用了不支持的 ID Token 签名算法。');
|
|
}
|
|
$keys = $this->document($this->endpoint($this->oidc['jwks_uri'] ?? ''));
|
|
$claims = (array) JWT::decode($encoded, JWK::parseKeySet($keys, $algorithm));
|
|
$audience = (array) ($claims['aud'] ?? []);
|
|
$client = $this->config['client_id'];
|
|
if (($claims['iss'] ?? null) !== $this->config['issuer'] || !in_array($client, $audience, true)
|
|
|| ((count($audience) > 1 || isset($claims['azp'])) && ($claims['azp'] ?? null) !== $client)
|
|
|| ($claims['nonce'] ?? null) !== $nonce || !is_string($claims['sub'] ?? null) || $claims['sub'] === ''
|
|
|| !is_int($claims['exp'] ?? null) || $claims['exp'] <= time()
|
|
|| !is_int($claims['iat'] ?? null) || $claims['iat'] > time() + 60) {
|
|
throw new RuntimeException('OIDC ID Token 声明校验失败。');
|
|
}
|
|
|
|
return $claims;
|
|
}
|
|
|
|
private function document(string $endpoint): array
|
|
{
|
|
$response = $this->http->get($this->endpoint($endpoint), ['headers' => ['Accept' => 'application/json'], 'stream' => true]);
|
|
$body = Utils::copyToString($response->getBody(), 1048577);
|
|
if (strlen($body) > 1048576 || $response->getStatusCode() !== 200) {
|
|
throw new RuntimeException('身份服务文档超过大小限制。');
|
|
}
|
|
$data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
|
|
if (!is_array($data)) {
|
|
throw new RuntimeException('身份服务文档格式无效。');
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
private function endpoint(mixed $endpoint): string
|
|
{
|
|
$url = is_string($endpoint) ? parse_url($endpoint) : false;
|
|
if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host'])
|
|
|| isset($url['user']) || isset($url['pass']) || isset($url['fragment']) || !Html::url($endpoint, true)) {
|
|
throw new RuntimeException('身份服务端点必须使用 HTTPS。');
|
|
}
|
|
|
|
return $endpoint;
|
|
}
|
|
}
|