nvn_trc/nvn_trc_oauth2

OAuth2-Client

v1.0.0 2023-03-06 07:50 UTC

This package is not auto-updated.

Last update: 2024-09-17 13:18:36 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查找正确的值,例如:https://: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

贡献

请参阅贡献指南以获取详细信息。

致谢

许可协议

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