Home > Enterprise >  Authentication using JWT in laravel
Authentication using JWT in laravel

Time:07-23

how to create a token in laravel that contains information about a user when he authenticates (login).

This is a login function in controller, when I decode the token, it doesn't contain information about user.!!

/**
 * Get a JWT token after successful login
 * @return \Illuminate\Http\JsonResponse
 */
public function login(Request $request){
    $validator = Validator::make($request->all(), [
        'email' => 'required|email',
        'password' => 'required|string|min:5',
    ]);

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);
    }

    if (! $token = JWTAuth::attempt($validator->validated())) {
        return response()->json(['status' => 'failed', 'message' => 'Invalid email and password.', 'error' => 'Unauthorized'], 401);
    }

    return $this->createNewToken($token);
}

CodePudding user response:

In your User model there should be method "getJWTCustomClaims" where you can add all the custom data you wish to be saved in token, like user group, special permission...

See https://jwt-auth.readthedocs.io/en/develop/quick-start/

This is in one of my projects:

    /**
     * @return array<string,string|int>
     */
    public function getJWTCustomClaims(): array
    {
        return [
            'group' => data_get($this, 'group'),
            'tenant' => data_get($this->tenant, 'id'),
        ];
    }
  • Related