matheen ulla
matheen ulla

Reputation: 558

how to create a JWT token with a role of a user ( Spatie JWT web token)

I want to pass the role of a user with a token after login. Instead of passing like below

 return response()->json([  
            'success' => true, 
            'access_token' => $token,
            'token_type' => 'bearer',
             'role' => auth('api')->user()->getRoleNames()
            /* 'expires_in' => auth('api')->factory()->getTTL() * 60 */
  ]);

I want to encode a role of a user with a JWT token. what I have tried

 public function login()
    {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->guard('api')->attempt($credentials)) {
            return response()->json(['errors' => 'In-valid username and Password'], 401);
        }
        return $this->respondWithToken($token);
    }

  protected function respondWithToken($token)
    {

        $role =auth('api')->user()->getRoleNames();
        $payload = JWTFactory::make($role); 
        $token = JWTAuth::encode($payload);

        return response()->json([  
            'success' => true, 
            'access_token' => $token,
            'token_type' => 'bearer',
        ]);
    }

when I tried this I am not getting a token. I have seen this documentation https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens to do this.

Thank you

Upvotes: 1

Views: 902

Answers (1)

matheen ulla
matheen ulla

Reputation: 558

Here we need to create our own token with user role.The code which work for me and it may help to others.

 public function login()
    {
        $credentials = request(['email', 'password']);

        if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials)) {
            return response()->json(['errors' => 'In-valid username and Password'], 401);
        }

        $token = auth('api')->claims(['role' => str_replace(['["', '"]', '/', '*'], '',auth('api')->user()->getRoleNames())])->attempt($credentials);
        return $this->respondWithToken($token);

    }

 protected function respondWithToken($token)
    {
        auth('api')->payload($token);
        return response()->json([  
            'success' => true, 
            'access_token' => $token,
            'token_type' => 'bearer',
        ]);
    }   


Upvotes: 1

Related Questions