stevenmaguire/oauth2-keycloak

The PHP League OAuth2-Client 的 Keycloak OAuth 2.0 客户端提供者

5.1.0 2023-10-24 06:10 UTC

README

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

此包为 PHP League 的 OAuth 2.0 客户端 提供Keycloak OAuth 2.0 支持。

安装

安装时使用 composer

composer require stevenmaguire/oauth2-keycloak

用法

用法与 The League 的 OAuth 客户端相同,使用 \Stevenmaguire\OAuth2\Client\Provider\Keycloak 作为提供者。

使用 authServerUrl 指定 Keycloak 服务器 URL。您可以从 Keycloak 客户端安装器 JSON 中的 auth-server-url 查找正确值,例如 http://localhost:8080/auth

使用 realm 指定 Keycloak 实体名称。您可以从 Keycloak 客户端安装器 JSON 中的 resource 查找正确值,例如 master

授权码流

$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
    'authServerUrl'         => '{keycloak-server-url}',
    'realm'                 => '{keycloak-realm}',
    'clientId'              => '{keycloak-client-id}',
    'clientSecret'          => '{keycloak-client-secret}',
    'redirectUri'           => 'https://example.com/callback-url',
    'encryptionAlgorithm'   => 'RS256',                             // optional
    'encryptionKeyPath'     => '../key.pem'                         // optional
    'encryptionKey'         => 'contents_of_key_or_certificate'     // optional
    'version'               => '20.0.1',                            // optional
]);

if (!isset($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: '.$authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    unset($_SESSION['oauth2state']);
    exit('Invalid state, make sure HTTP sessions are enabled.');

} else {

    // Try to get an access token (using the authorization coe grant)
    try {
        $token = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);
    } catch (Exception $e) {
        exit('Failed to get access token: '.$e->getMessage());
    }

    // 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 user's details
        $user = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $user->getName());

    } catch (Exception $e) {
        exit('Failed to get resource owner: '.$e->getMessage());
    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();
}

刷新令牌

$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
    'authServerUrl'     => '{keycloak-server-url}',
    'realm'             => '{keycloak-realm}',
    'clientId'          => '{keycloak-client-id}',
    'clientSecret'      => '{keycloak-client-secret}',
    'redirectUri'       => 'https://example.com/callback-url',
]);

$token = $provider->getAccessToken('refresh_token', ['refresh_token' => $token->getRefreshToken()]);

处理加密

如果您已配置您的 Keycloak 实例使用加密,则有一些高级选项可供您使用。

配置提供者使用相同的加密算法

$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
    // ...
    'encryptionAlgorithm'   => 'RS256',
]);

$provider->setEncryptionAlgorithm('RS256');

配置提供者使用预期的解密公钥或证书

通过密钥值
$key = "-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----";
// or
// $key = "-----BEGIN CERTIFICATE-----\n....\n-----END CERTIFICATE-----";

$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
    // ...
    'encryptionKey'   => $key,
]);

$provider->setEncryptionKey($key);
通过密钥路径
$keyPath = '../key.pem';

$provider = new Stevenmaguire\OAuth2\Client\Provider\Keycloak([
    // ...
    'encryptionKeyPath'   => $keyPath,
]);

$provider->setEncryptionKeyPath($keyPath);

测试

$ ./vendor/bin/phpunit

贡献

请参阅 CONTRIBUTING 了解详情。

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件