How to add custom data to Laravel Passport API token?

Viewed 1423

I am using Laravel Passport and I would like to know if it is possible to add custom data to the Laravel\Passport\Token:

//This is how I create the token
$user = $request->user();
$token = $user->createToken('ACCESS_TOKEN')->accessToken;

I send the token to the API with the header Authorization: Bearer ${token}

Is there any way I can add custom information to the token? Something like this:

$token->customField = 'custom value';
$value = $request->user()->token()->customField;

I've read the Passport Docs but there is no info about that.

2 Answers

No, this is not supported in Passport by default, but it has been requested.

Custom data is supported by JWTs by using custom claims. Passport does not provide the ability to add custom claims to the JWT, but it looks like someone made a package to add the functionality: https://github.com/corbosman/laravel-passport-claims.

From a quick look, it looks like you'll be able to add custom claims to the JWT, but I don't see any helpers or anything for reading that data back. You'd have to parse the token and get the claim yourself:

$jwtParser = app()->make(\Lcobucci\JWT\Parser::class);
$claimValue = $jwtParser->parse('your-bearer-token')->getClaim('your-claim-name');

NB: I've never done this myself, I've never used that package, and everything here is untested.

You can add it manually, by creating migration file with your custom field.

public function up()
{
    Schema::table('oauth_access_tokens', function (Blueprint $table) {
        $table->string('customField',20)->after('client_id')->nullable();
    });
    
}

After the tokenCreate() add the filed value to the table:

$token = $user->createToken($user->email);
DB::table('oauth_access_tokens')
           ->where('id', $token->token->id)
           ->update(['customField' => $request->customField]);
Related