Jwt-auth: How can I create a token with custom claims from a user

Created on 11 Nov 2017  路  5Comments  路  Source: tymondesigns/jwt-auth

In the previous version all I had to do was:

JWTAuth::fromUser($user, ['exp' => Carbon::now()->addYear()->timestamp, 'typ' => 'refresh'])

In the 1.0.0-rc.1 version all of this is gone. Is there a simple way for me to reproduce what I did? It would save me from re-writing a ton of already implemented and tested code.

Most helpful comment

You can make it directly from User model, example:
public function getJWTCustomClaims()
{
return ['firstname' => $this->firstname,
'lastname' => $this->lastname,
'email' => $this->email];
}

All 5 comments

You can make it directly from User model, example:
public function getJWTCustomClaims()
{
return ['firstname' => $this->firstname,
'lastname' => $this->lastname,
'email' => $this->email];
}

@bmbBAMBUS I use that function to create the main token, but what I need to do is create a separate token with different custom claims than what is in getJWTCustomClaims()

I'm having the same issue, I need 2 different tokens, one for normal authentication and another, with different duration, for different purposes, I'm struggling with trying to figure out the source code on my own to add custom claims to make my own custom token.

To be honest, you are likely better off just rolling with a basic JWT library and creating a class to do what you need.

I actually ended up just switching to Laravel Passport as it did what I needed for the most part, and it is supported quite well.

You can simply use the claims() setter:

$token = auth()->claims(['foo' => 'bar'])->attempt($creds);
$token = auth()->claims(['foo' => 'bar'])->login($user);
// etc
Was this page helpful?
0 / 5 - 0 ratings

Related issues

agneshoving picture agneshoving  路  3Comments

gandra picture gandra  路  3Comments

therealmjk picture therealmjk  路  3Comments

harveyslash picture harveyslash  路  3Comments

hfalucas picture hfalucas  路  3Comments