Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Passport jwt additional claims
<?php
namespace App\Auth;
use Laravel\Passport\Bridge\AccessToken as BaseToken;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use League\OAuth2\Server\CryptKey;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Entities\ScopeEntityInterface;
class AccessToken extends BaseToken
{
/**
* Generate a JWT from the access token
*
* @param CryptKey $privateKey
*
* @return string
*/
public function convertToJWT(CryptKey $privateKey)
{
$builder = new Builder();
$builder->setAudience($this->getClient()->getIdentifier())
->setId($this->getIdentifier(), true)
->setIssuedAt(time())
->setNotBefore(time())
->setExpiration($this->getExpiryDateTime()->getTimestamp())
->setSubject($this->getUserIdentifier())
->set('scopes', $this->getScopes());
if ($user = \App\User::find($this->getUserIdentifier())) {
$builder
->set('uid', $user->uuid)
->set('parent_id', $user->parent_id)
->set('name', $user->display_name)
->set('email', $user->email)
->set('avatar', $user->avatar)
->set('admin', $user->hasRole('admin'))
->set('roles', $user->roleList())
->set('permissions', $user->permissionList())
->set('plan', $user->getCurrentPlanName());
// Basically anything the the jwt consumers should be able to access without hitting the server
}
return $builder
->sign(new Sha256(), new Key($privateKey->getKeyPath(), $privateKey->getPassPhrase()))
->getToken();
}
}
<?php
namespace App\Auth;
use Laravel\Passport\Bridge\AccessTokenRepository as BaseRepository;
use League\OAuth2\Server\Entities\ClientEntityInterface;
// This class exists just to return the custom token instead of the default
class AccessTokenRepository extends BaseRepository
{
/**
* {@inheritdoc}
*/
public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
{
return new AccessToken($userIdentifier, $scopes);
}
}
<?php
namespace App\Providers;
...
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Laravel\Passport\Bridge\AccessTokenRepository;
class AuthServiceProvider extends ServiceProvider
{
...
public function register()
{
$this->app->bind(AccessTokenRepository::class, function ($app) {
return $app->make(\App\Auth\AccessTokenRepository::class);
});
}
}
@lloy0076

This comment has been minimized.

Copy link

@lloy0076 lloy0076 commented Jan 29, 2017

@RDelorier - looks good to me :)

@tzkmx

This comment has been minimized.

Copy link

@tzkmx tzkmx commented Feb 22, 2021

I wonder if this changed with passport 10 as there are comments about League Server changed token handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment