How to set custom payload/Claims on Laravel JWT?

The payload will carry the bulk of our JWT, also called the JWT Claims. This is where we will put the information that we want to transmit and other extra information about our token.

There are multiple claims that we can provide. This includes registered claim names, public claim names, and private claim names.

Public claims that we create ourselves like username, information, and other important information.

So I wanted to send user information with the token in my open source project Laravel AdminPanel which is in Laravel 5.6 and I’ve used “tymon/jwt-auth”: “2.0.x-dev“. In the Latest version of tymon/jwt-auth , they have changed the way to add custom claims and document is not completed yet.

we need to implement the interface JWTSubject to our User model.

class User extends Authenticatable implements JWTSubject{
public function getJWTCustomClaims()
{
return [
'id' => $this->id,
'first_name' => $this->first_name,
'last_name' => $this->last_name,
'email' => $this->email,
'picture' => $this->getPicture(),
'confirmed' => $this->confirmed,
'registered_at' => $this->created_at->toIso8601String(),
'last_updated_at' => $this->updated_at->toIso8601String(),
];
}
}

Please don’t forgot to import JWTSubject :
use Tymon\JWTAuth\Contracts\JWTSubject;

If we want to access custom claims we can do it as mentioned below.

JWTAuth::getPayload();
JWTAuth::getPayload()->get('first_name');

Hope it helps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s