PHPackages                             pviojo/oauth2-keycloak - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. pviojo/oauth2-keycloak

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

pviojo/oauth2-keycloak
======================

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2.0.2(8y ago)464.8k23MITPHP

Since Aug 31Pushed 8y ago1 watchersCompare

[ Source](https://github.com/pviojo/oauth2-keycloak)[ Packagist](https://packagist.org/packages/pviojo/oauth2-keycloak)[ RSS](/packages/pviojo-oauth2-keycloak/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (8)Used By (3)

Keycloak Provider for OAuth 2.0 Client
======================================

[](#keycloak-provider-for-oauth-20-client)

[![Latest Version](https://camo.githubusercontent.com/0b234ac733400ca1680c1f4e4c9ffe73679c02168c61bf81ae40f5a8aa40eaa5/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f7076696f6a6f2f6f61757468322d6b6579636c6f616b2e7376673f7374796c653d666c61742d737175617265)](https://github.com/pviojo/oauth2-keycloak/releases)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Total Downloads](https://camo.githubusercontent.com/1bdfc46ffc32704ddde06dc1e830663e8f44f710948c5fab3bdfa8019ef30c86/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f7076696f6a6f2f6f61757468322d6b6579636c6f616b2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/pviojo/oauth2-keycloak)

This package provides Keycloak OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

Installation
------------

[](#installation)

To install, use composer:

```
composer require pviojo/oauth2-keycloak

```

Usage
-----

[](#usage)

Usage is the same as The League's OAuth client, using `\pviojo\OAuth2\Client\Provider\Keycloak` as the provider.

Use `authServerUrl` to specify the Keycloak server URL. You can lookup the correct value from the Keycloak client installer JSON under `auth-server-url`, eg. `http://localhost:8080/auth`.

Use `realm` to specify the Keycloak realm name. You can lookup the correct value from the Keycloak client installer JSON under `resource`, eg. `master`.

### Authorization Code Flow

[](#authorization-code-flow)

```
$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',
    'encryptionAlgorithm'   => 'RS256',                             // optional
    'encryptionKeyPath'     => '../key.pem'                         // optional
    'encryptionKey'         => 'contents_of_key_or_certificate'     // 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();
}
```

### Refreshing a Token

[](#refreshing-a-token)

```
$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()]);
```

### Getting user roles

[](#getting-user-roles)

After authenticating retrieve roles from the resource owner.

```
$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)
```

### Handling encryption

[](#handling-encryption)

If you've configured your Keycloak instance to use encryption, there are some advanced options available to you.

#### Configure the provider to use the same encryption algorithm

[](#configure-the-provider-to-use-the-same-encryption-algorithm)

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

or

```
$provider->setEncryptionAlgorithm('RS256');
```

#### Configure the provider to use the expected decryption public key or certificate

[](#configure-the-provider-to-use-the-expected-decryption-public-key-or-certificate)

##### By key value

[](#by-key-value)

```
$key = "-----BEGIN PUBLIC KEY-----\n....\n-----END PUBLIC KEY-----";
// or
// $key = "-----BEGIN CERTIFICATE-----\n....\n-----END CERTIFICATE-----";

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

or

```
$provider->setEncryptionKey($key);
```

##### By key path

[](#by-key-path)

```
$keyPath = '../key.pem';

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

or

```
$provider->setEncryptionKeyPath($keyPath);
```

Testing
-------

[](#testing)

```
$ ./vendor/bin/phpunit
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/pviojo/oauth2-keycloak/blob/master/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Pablo Viojo](https://github.com/pviojo)
- [Steven Maguire](https://github.com/stevenmaguire)
- [All Contributors](https://github.com/pviojo/oauth2-keycloak/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/pviojo/oauth2-keycloak/blob/master/LICENSE) for more information.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity31

Limited adoption so far

Community17

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 68.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~155 days

Recently: every ~78 days

Total

6

Last Release

3129d ago

Major Versions

0.2.0 → 1.x-dev2016-12-09

1.x-dev → 2.0.02017-01-26

### Community

Maintainers

![](https://www.gravatar.com/avatar/94e6aa44e70a71f74dfde92b1816d3eab7b26af5a87c28e1b5b89a851659119e?d=identicon)[pviojo](/maintainers/pviojo)

---

Top Contributors

[![stevenmaguire](https://avatars.githubusercontent.com/u/1851973?v=4)](https://github.com/stevenmaguire "stevenmaguire (15 commits)")[![raehalme](https://avatars.githubusercontent.com/u/3288306?v=4)](https://github.com/raehalme "raehalme (6 commits)")[![pviojo](https://avatars.githubusercontent.com/u/16887?v=4)](https://github.com/pviojo "pviojo (1 commits)")

---

Tags

clientoauthoauth2authorizationrolesauthorisationkeycloak

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/pviojo-oauth2-keycloak/health.svg)

```
[![Health](https://phpackages.com/badges/pviojo-oauth2-keycloak/health.svg)](https://phpackages.com/packages/pviojo-oauth2-keycloak)
```

###  Alternatives

[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2509.6M48](/packages/thenetworg-oauth2-azure)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
