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.
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
Most helpful comment
In App\User
add
public function getJWTCustomClaims() { return [ 'user_nickname' => $this->user_nickname, ]; }