tymondesigns / jwt-auth

🔐 JSON Web Token Authentication for Laravel & Lumen
https://jwt-auth.com
MIT License
11.29k stars 1.54k forks source link

How do we customise the claims? #2228

Open kirkbushell opened 1 year ago

kirkbushell commented 1 year ago

I have a "multi-tenant" game application, and instead of having to store the accessed account in the URL, I want it to be part of the JWT token payload. So, a user can login to an account, and that account will be stored as part of the payload.

However, I also want them to be able to switch accounts. This would involve another endpoint, and then I issue the user a new token to be used.

On subsequent requests I would check check the game they've switched to and double-check they can access.

But this saves having to swap domains or have a URL prefix (which I don't want, in this context it doesn't make any sense).

azzumed commented 10 months ago

use customClaims method

Ramazanonat commented 9 months ago

use customClaims method

i did that.

Add those on User model // public function getJWTIdentifier() { return $this->getKey(); }

public function getJWTCustomClaims()
{
    return $this->jwtCustomClaims;
}

public function setJWTCustomClaims(array $claims)
{
    $this->jwtCustomClaims = $claims;
}

// then u can use setJWTCustomClaims method like that. // if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) { $user = Auth::user(); $user->setJWTCustomClaims(['test' => 'test']); $token = JWTAuth::fromUser($user);

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

//