Jwt-auth: Is there any way to add user data in token payload on "attempt"?

Created on 1 Aug 2017  路  4Comments  路  Source: tymondesigns/jwt-auth

Basically, when authenticating, how can I pass a user data to the token payload?

For instance, what should I do in this piece of code to my token payload include the user name?

        $credentials = $request->only('email', 'password');

        try {
            if (! $token = JWTAuth::attempt($credentials)) { // I want to add the user name in the token
                return response()->json(['error' => 'invalid_credentials'], 422);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'auth_error'], 500);
        }

I know there's Creating a Token Based on Anything You Like, but you would hit the DB multiple times which is crappy....

It's related to #89 but nobody answers there, so I'm creating a related issue, many things have changed since.

Most helpful comment

In App\User

add
public function getJWTCustomClaims() { return [ 'user_nickname' => $this->user_nickname, ]; }

All 4 comments

Also, it would be just as bad to use laravel's default auth since it's not stateless and creates useless sessions and logs.... so, yeah.. i have no idea what to do.

My solution was to manually make all auth steps and forget about the attempt method.

In my case, the steps were: querying for the user email, checking the password hash, the active conditions then creating the token...

If anyone is interested:

```php
$credentials = $request->only('email', 'password');

$user = User::where('email', $credentials['email'])->firstOrFail();

if (!Hash::check($credentials['password'], $user->password)) {
return response()->json(['error' => 'invalid_credentials'], 422);
}

if ($user->active === 0) {
return response()->json(['error' => 'inactive_user'], 403);
}

try {
$customClaims = ['name' => $user->name]; // Here you can pass user data on claims
$token = JWTAuth::fromUser($user, $customClaims);
} catch (JWTException $e) {
return response()->json(['error' => 'auth_error'], 500);
}
```

EDIT: _PS: Don't forget to use Illuminate\Support\Facades\Hash;_

In App\User

add
public function getJWTCustomClaims() { return [ 'user_nickname' => $this->user_nickname, ]; }

confirm @RJustice solution for v1 on laravel 5.5

Was this page helpful?
0 / 5 - 0 ratings

Related issues

harveyslash picture harveyslash  路  3Comments

mihailo-misic picture mihailo-misic  路  3Comments

Rasoul-Karimi picture Rasoul-Karimi  路  3Comments

johncloud200 picture johncloud200  路  3Comments

heroghost picture heroghost  路  3Comments