Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add the user role to the jwt, laravel 5 jwt-auth

Tags:

php

laravel

jwt

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 ?

like image 807
RVandersteen Avatar asked Mar 12 '15 16:03

RVandersteen


1 Answers

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])
like image 181
Olatunde Alex-Oni Avatar answered Sep 23 '22 10:09

Olatunde Alex-Oni