Custom payload with Laravel JWT

11,218

Solution 1

Try below code is working for me.

//load user place your code for load user
$user = User::find( $user_id );
// if you don't have user id then also you can used.
$user = User::where( 'email', $tokenPayload->email )->first();

$payloadable = [
        'id' => $tokenPayload->id,
        'name' => $tokenPayload->name,
        'email' => $tokenPayload->email,
        'deleted_at' => $tokenPayload->deleted_at,
        'created_at' => $tokenPayload->created_at,
        'updated_at' => $tokenPayload->updated_at,
        'organization' => $request->organization_id
    ];

$token = JWTAuth::fromUser($user,$payloadable);

you can get organization using below code.

$payload = JWTAuth::parseToken()->getPayload();
// then either of
$payload->get('organization');

you can get new token using fromUser method by passing the user object.

try this code I hope this code is working for you.

You can get more detail from here.

Solution 2

You return the $token, but use $token->get() instead.

return response()->json(['token' => $token->get()]);

This should call the __toString().

Solution 3

The way I add custom payload in my controller:

    $customClaims = ['foo' => 'bar', 'baz' => 'bob'];
    $token = JWTAuth::claims($customClaims)->attempt($credentials);

The way I get back my custom payload:

    dd(auth()->payload()->get('foo'));

Solution 4

This solution was tested on tymon/jwt-auth 1.0.0

use JWTAuth;
use Tymon\JWTAuth\Facades\JWTFactory;

//...

$user = User::find(1);

$payload = JWTFactory::sub($user->id)
    ->myCustomString('Foo Bar')
    ->myCustomArray(['Apples', 'Oranges'])
    ->myCustomObject($user)
    ->make();

$token = JWTAuth::encode($payload);

return response()->json(['token' => $token]);

The code above will return a token that represents:

{
    "iss": "http://yourdomain.com", //Automatically inserted
    "iat": 1592808100,              //Automatically inserted
    "exp": 1592811700,              //Automatically inserted
    "nbf": 1592808100,              //Automatically inserted
    "jti": "wIyXAEvPk64nyH3C"       //Automatically inserted
    "sub": 1,                       //User ID (required)
    "myCustomString": "Foo Bar",
    "myCustomArray":  ["Apples", "Oranges"],
    "myCustomObject": { ... } //Full $user object
}
Share:
11,218
rakibtg
Author by

rakibtg

do do doing did done ~ @rakibtg

Updated on June 17, 2022

Comments

  • rakibtg
    rakibtg almost 2 years

    I am using Laravel 5.3 and laravel jwt for token, here is the list of namespaces used by the controller.

    use JWTAuth;
    use App\Http\Requests;
    use Illuminate\Http\Request;
    use Tymon\JWTAuth\Facades\JWTFactory;
    use Tymon\JWTAuth\Exceptions\JWTException;
    

    I need to add custom payload data to generate the token.

    Here is how i am trying to generate token with custom payloads.

            $payloadable = [
                'id' => $tokenPayload->id,
                'name' => $tokenPayload->name,
                'email' => $tokenPayload->email,
                'deleted_at' => $tokenPayload->deleted_at,
                'created_at' => $tokenPayload->created_at,
                'updated_at' => $tokenPayload->updated_at,
                'organization' => $request->organization_id
            ];
    
            // Generate the token.
            $token = JWTAuth::encode( JWTFactory::make( $payloadable ) );
    
            // Return token.
            return response()->json( [ 'token' => $token ] );
    

    But in the response the token is empty! Here is the response

    {
      "token": {}
    }
    

    Why it is returning an empty token instead of a jwt token!

    Update:

    Now i can get the token using a \ before the JWTFactory namespace, but how I will be able to get the updated token value?

    What I am trying to achive is to add some additional fields to an existing token, after reading Laravel JWT-auth doc, i figured out that i need to create another token which would have the additional fields but the new token is not returning additional fields.