I have a laravel 5 backend that sends an jwt-token as a json response on login with jwt-auth.
Now I would like to add the user role to the jwt token that laravel sends, I tried the following way:
This is my current controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Database\Eloquent\Model;
use App\User;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
$user = User::where('email', '=', $credentials['email'])->first();
$customClaims = ['role' => $user->role];
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials, $customClaims)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}
?>
Is there a cleaner way to do this ?
You are currently querying for the user twice, once using the email for the purpose of getting the role and the second within the jwt::attempt()
method.I would suggest reducing the queries to just one but doing the authentication {Auth::attempt($credientials)} and then
passing the retrieved user into JWT::fromUser()
method, along with the custom claim. so
JWT::fromUser($user,['role' => $user->role])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With