thephpleague / oauth2-server

A spec compliant, secure by default PHP OAuth 2.0 Server
https://oauth2.thephpleague.com
MIT License
6.52k stars 1.12k forks source link

BC support of Custom Claims #1222

Closed ElisDN closed 3 years ago

ElisDN commented 3 years ago

Easy backward compatible way for parsing custom claims for #1120, #1122 and #1183 in the next 8.x release.

How to use it

For example, if you want to add a role field into JWT, just add $role property into your token entity and override convertToJWT method from trait for adding role claim:

class AccessToken implements AccessTokenEntityInterface
{
    // ...

    private $userRole;

    public function setUserRole($role) { $this->userRole = $role }
    public function getUserRole() { return $this->userRole }

    private function convertToJWT()
    {
        return $this->jwtConfiguration->builder()
            // ...
            ->withClaim('role', $this->getUserRole())
            // ...
    }
}

After all fetch user role and fill the property in token repository:

class AccessTokenRepository implements AccessTokenRepositoryInterface
{
    // ...

    public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
    {
        $accessToken = new AccessTokenEntity();
        // ...

        if ($userIdentifier !== null) {
            $accessToken->setUserIdentifier($userIdentifier);

            $row = $this->db->query('SELECT role FROM users WHERE id = :id', ['id' => $userIdentifier]);
            $accessToken->setUserRole($row['role']);
        }

        return $accessToken;
    }

    // ...
}

And now you can retreive $request->getAttribute('oauth_custom_claims') with value like ['role' => 'admin'].

Sephster commented 3 years ago

Thanks @ElisDN - this is a simple solution but does require overriding of existing functions. I think ideally, long term, I'd like something more deliberately baked into the package. There are a few other potential PRs which go further than this one so for that reason, I won't be proceeding with this at present.

Thank you for your efforts though and apologies I won't be merging this in at this time.

systemsolutionweb commented 1 year ago

@Sephster neither this nor the other

vrusua commented 1 year ago

@Sephster is there any PR finally considered to add custom claims support? It's so useful for SPA and actually discussing here for a couple of years. Thanks.

Sephster commented 1 year ago

Definitely want to add this so not off the radar