senyahnoj/oauth2-keycloak

PHP League OAuth2-Client 的 Keycloak OAuth 2.0 客户端提供程序

2.1.0 2022-06-21 15:04 UTC

This package is not auto-updated.

Last update: 2024-09-26 00:34:54 UTC


README

Latest Version Software License Total Downloads

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

安装

要安装,请使用 composer

composer require pviojo/oauth2-keycloak

用法

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

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

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

授权码流

$provider = new pviojo\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'
]);

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 pviojo\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()]);

获取用户角色

在认证后从资源所有者检索角色。

$user = $provider->getResourceOwner($token);
$roles = $user->getRoles(); //retrieve all roles
$rolesClient = $user->getRolesForClient($client); //retrieve all roles for given $client
$hasRole = $user->hasRoleForClient($client, $role); //check if user has the $role for  $client
$hasAccess = $user->hasAccessToClient($client, $role); //check if user has access to $client (at least one role)

测试

$ ./vendor/bin/phpunit

贡献

请参阅 CONTRIBUTING 了解详细信息。

鸣谢

许可协议

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