Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom payload with Laravel JWT

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.

like image 450
rakibtg Avatar asked Nov 05 '16 07:11

rakibtg


People also ask

Does laravel sanctum use JWT?

Yes because both Laravel passport and Laravel sanctum uses JWT for authorization and no because the Laravel framework itself has nothing to do with JWT.

Does laravel passport use JWT?

Passport uses JWT authentication as standard but also implements full OAuth 2.0 authorization.

What is the difference between JWT and passport laravel?

JWT - is a simple JSON Web Token, it simply gives a token to the user that can be used to login, this token will never expire (Passport tokens will expire and the client will need to update the token with the refresh token)

What is the use of JSON Web Token?

A JSON web token(JWT) is JSON Object which is used to securely transfer information over the web(between two parties). It can be used for an authentication system and can also be used for information exchange. The token is mainly composed of header, payload, signature. These three parts are separated by dots(.).


3 Answers

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
}
like image 179
Fred Vanelli Avatar answered Oct 16 '22 01:10

Fred Vanelli


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'));
like image 30
W Kenny Avatar answered Oct 16 '22 01:10

W Kenny


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.

like image 25
Renish Khunt Avatar answered Oct 16 '22 03:10

Renish Khunt