PHPackages                             dalpras/oauth2-openid-server - 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. dalpras/oauth2-openid-server

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

dalpras/oauth2-openid-server
============================

OpenID Server that works with PHP League's OAuth2 Server

v6.1(3mo ago)315MITPHPPHP &gt;=8.2

Since Jan 29Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/dalpras/oauth2-openid-server)[ Packagist](https://packagist.org/packages/dalpras/oauth2-openid-server)[ RSS](/packages/dalpras-oauth2-openid-server/feed)WikiDiscussions master Synced yesterday

READMEChangelog (4)Dependencies (2)Versions (15)Used By (0)

OAuth 2.0 OpenID Server
=======================

[](#oauth-20-openid-server)

This implements the OpenID specification on top of The PHP League's [OAuth2 Server](https://github.com/thephpleague/oauth2-server).
This library is based on the work of [OAuth 2.0 OpenID Server](https://github.com/steverhoades/oauth2-openid-connect-client).

Requirements
------------

[](#requirements)

- Requires PHP version 7.3 or greater.
- [league/oauth2-server](https://github.com/thephpleague/oauth2-server) 8.0 or greater.
- [lcobucci/jwt](https://github.com/lcobucci/jwt) 4.0 or greater.

Usage
-----

[](#usage)

The following classes will need to be configured and passed to the AuthorizationServer in order to provide OpenID functionality.

1. IdentityRepository.
    This MUST implement the DalPraS\\OpenId\\Server\\Repositories\\IdentityRepositoryInterface and return the identity of the user based on the return value of $accessToken-&gt;getUserIdentifier(). 1.1 The IdentityRepository MUST return a UserEntity that implements the following interfaces 1.2 DalPraS\\OpenId\\Server\\Entities\\ClaimSetInterface 1.3 League\\OAuth2\\Server\\Entities\\UserEntityInterface.
2. ClaimSet.
    ClaimSet is a way to associate claims to a given scope.
3. ClaimExtractor.
    The ClaimExtractor is an ArrayObject of ClaimSets. You can append ClaimSet to the ArrayObject via `append` and then extract the uset claims.
4. OidcResponse.
    This class must be passed to the AuthorizationServer during construction and is responsible for adding the id\_token to the response. The access\_token is formatted as a Json Web Token (data is inside signed and encripted inside the token).
5. ScopeRepository.
    The getScopeEntityByIdentifier($identifier) method must return a ScopeEntity for the `openid` scope in order to enable support. See examples.

### Example Configuration

[](#example-configuration)

```
// Init Repositories
$clientRepository       = new ClientRepository();
$scopeRepository        = new ScopeRepository();
$accessTokenRepository  = new AccessTokenRepository();
$authCodeRepository     = new AuthCodeRepository();
$refreshTokenRepository = new RefreshTokenRepository();

$privateKeyPath = 'file://' . __DIR__ . '/../private.key';
$publicKeyPath = 'file://' . __DIR__ . '/../public.key';

// OpenID Response Type
$oidcResponse = new OidcResponse();
$oidcResponse->setIdentityRepository(new IdentityRepository());
$oidcResponse->setClaimExtractor(new ClaimExtractor());

// Setup the authorization server
$server = new \League\OAuth2\Server\AuthorizationServer(
    $clientRepository,
    $accessTokenRepository,
    $scopeRepository,
    $privateKey,
    $publicKey,
    $oidcResponse
);

$grant = new \DalPraS\OpenId\Server\Grant\OidcAuthCodeGrant($authCodeRepository, $refreshTokenRepository,
            new \DateInterval(self::TTL_AUTH_CODE));

$grant->setRefreshTokenTTL(new \DateInterval('P1M')); // refresh tokens will expire after 1 month

// Enable the authentication code grant on the server
$server->enableGrantType(
    $grant,
    new \DateInterval('PT1H') // access tokens will expire after 1 hour
);

return $server;
```

After the server has been configured it should be used as described in the [OAuth2 Server documentation](https://oauth2.thephpleague.com/).

Authorization code endpoint
---------------------------

[](#authorization-code-endpoint)

```
    try {
        // Validate the HTTP request and return an AuthorizationRequest object.
        // The auth request object can be serialized into a user's session
        $authRequest = $server->validateAuthorizationRequest($request);

        // Once the user has logged in set the user on the AuthorizationRequest
        $authRequest->setUser($user);

        // Once the user has approved or denied the client update the status
        // (true = approved, false = denied)
        $authRequest->setAuthorizationApproved(true);

        // Return the HTTP redirect response
        return $server->completeAuthorizationRequest($authRequest, $response);

    } catch (OAuthServerException $e) {
        return $e->generateHttpResponse($response);

    } catch (\Exception $e) {
        return (new OAuthServerException($e->getMessage(), 0, 'unknown_error', 500))->generateHttpResponse($response);
    }
```

For an access\_token endpoint is possible to use the middlewares:

```
    $claimExtractor = new \DalPraS\OpenId\Server\ClaimExtractor();

    // OpenID Response
    $oidcResponse = new OidcResponse($userRepo, $claimExtractor);

    // Setup the authorization server
    $authServer = new \League\OAuth2\Server\AuthorizationServer(
        $clientRepo,
        $accessTokenRepo,
        $scopeRepo,
        $privateKeyPath,
        'XXXX_XXX_XXX_XXX_XX',
        $oidcResponse
    );

    // OpenID Response Type instead of Bearer
    $middleware = new AuthorizationServerMiddleware($this->getAuthServer());
    return $middleware->__invoke($psrRequest, $psrResponse, function($request, $response) {
        return $response;
    });
```

UserEntity
----------

[](#userentity)

In order for this library to work properly you will need to add your IdentityProvider to the IdTokenJwtResponse object. This will be used internally to lookup a UserEntity by it's identifier.
Additionally your UserEntity must implement the ClaimSetInterface which includes a single method getClaims(). The getClaims() method should return a list of attributes as key/value pairs that can be returned if the proper scope has been defined.

```
    use League\OAuth2\Server\Entities\Traits\EntityTrait;
    use League\OAuth2\Server\Entities\UserEntityInterface;
    use DalPraS\OpenId\Server\Entities\ClaimSetInterface;

    class UserEntity implements UserEntityInterface, ClaimSetInterface
    {
        use EntityTrait;

        protected $attributes;

        public function getClaims()
        {
            return $this->attributes;
        }
    }
```

ClaimSets
---------

[](#claimsets)

A ClaimSet is a scope that defines a list of claims.

```
// Example of the profile ClaimSet
$claimSet = new ClaimSetEntity('profile', [
        'name',
        'family_name',
        'given_name',
        'middle_name',
        'nickname',
        'preferred_username',
        'profile',
        'picture',
        'website',
        'gender',
        'birthdate',
        'zoneinfo',
        'locale',
        'updated_at'
    ]);
```

As you can see from the above, profile lists a set of claims that can be extracted from our UserEntity if the profile scope is included with the authorization request.

### Adding Custom ClaimSets

[](#adding-custom-claimsets)

At some point you will likely want to include your own group of custom claims. To do this you will need to create a ClaimSetEntity, give it a scope (the value you will include in the scope parameter of your OAuth2 request) and the list of claims it supports.

```
    $extractor = new ClaimExtractor();
    // Create your custom scope
    $claimSet = new ClaimSetEntity('company', [
            'company_name',
            'company_phone',
            'company_address'
        ]);
    // Add it to the ClaimExtract (this is what you pass to IdTokenResponse, see configuration above)
    $extractor->addClaimSet($claimSet);
```

Now, when you pass the company scope with your request it will attempt to locate those properties from your UserEntity::getClaims().

Install
-------

[](#install)

Via Composer

```
    composer require dalpras/oauth2-openid-server
```

Testing
-------

[](#testing)

Sorry, didnt' have time for writing standalone tests ...

To run the unit tests you will need to require league/oauth2-server from the source as this repository utilizes some of their existing test infrastructure.

```
    composer require league/oauth2-server --prefer-source
```

Run PHPUnit from the root directory:

```
    vendor/bin/phpunit
```

License
-------

[](#license)

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

###  Health Score

48

—

FairBetter than 94% of packages

Maintenance80

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity80

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 87.5% 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 ~196 days

Recently: every ~449 days

Total

14

Last Release

106d ago

Major Versions

v1.0 → v2.02019-06-19

v2.1 → v3.02020-03-10

v3.1 → v4.02020-12-22

v4.2 → v5.02021-02-15

v5.3 → v6.02024-05-22

PHP version history (3 changes)v2.1PHP &gt;=7.2.0

v5.0PHP &gt;=7.3

v5.3PHP &gt;=8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/f4ad7c52ee1f0a8936e8bb6bcc95f15d4f55ce63233a0fa629da25bba024bd97?d=identicon)[dalpras](/maintainers/dalpras)

---

Top Contributors

[![dalpras-vimar](https://avatars.githubusercontent.com/u/174025991?v=4)](https://github.com/dalpras-vimar "dalpras-vimar (14 commits)")[![dalpras](https://avatars.githubusercontent.com/u/11516569?v=4)](https://github.com/dalpras "dalpras (2 commits)")

### Embed Badge

![Health badge](/badges/dalpras-oauth2-openid-server/health.svg)

```
[![Health](https://phpackages.com/badges/dalpras-oauth2-openid-server/health.svg)](https://phpackages.com/packages/dalpras-oauth2-openid-server)
```

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[php-open-source-saver/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

8359.8M53](/packages/php-open-source-saver-jwt-auth)[steverhoades/oauth2-openid-connect-server

An OpenID Connect Server that sites on The PHP League's OAuth2 Server

2097.8M12](/packages/steverhoades-oauth2-openid-connect-server)[scheb/2fa

Two-factor authentication for Symfony applications (please use scheb/2fa-bundle to install)

578630.7k1](/packages/scheb-2fa)[jeremy379/laravel-openid-connect

OpenID Connect support to the PHP League's OAuth2 Server. Compatible with Laravel Passport.

55342.3k2](/packages/jeremy379-laravel-openid-connect)[patrickbussmann/oauth2-apple

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

1132.5M6](/packages/patrickbussmann-oauth2-apple)

PHPackages © 2026

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