JWT Auth custom user token

1.8k views Asked by At

I'm using laravel 5 and JWTauth package. I'm wondering if it's possible to use a custom token to authenticate a user. Instead of encoding the user's full details, just encode id and email.

The reason why I want to do this is because every time the user updates his details, the app needs to generate new token and update the header bearer token. Otherwise the token is invalid. Is there other way/better way to do this?

I would appreciate your recommendation. Thanks!

1

There are 1 answers

0
larslemos On

You can obtain the token in this way.

$user = User::first();

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

or

try {
                //attempt to verify the credentials and create a token for the user
                if(!$userToken = JWTAuth::attempt($credentials)) {
                    return response()->json(['error' => 'invalid_credentials'], 401);
                }
            } catch(JWTException $e) {
                return response()->json(['error' => 'could_not_create_token'], 500);
            }