tymondesigns / jwt-auth

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

Performance consideration when only user id is needed #2220

Open mouhong opened 1 year ago

mouhong commented 1 year ago

Performance consideration when only user id is needed

Sometimes we just need to use auth('api')->id() to retrieve the login user's id only. However, the id() function provided by Laravel's GuardHelper simply delegates call to user() and then returns the user's id:

public function id()
{
    if ($this->user()) {
        return $this->user()->getAuthIdentifier();
    }
}

Which means it'll always trigger a db call to retrieve the full user info even if only the id is needed.

public function user()
{
    if ($this->user !== null) {
        return $this->user;
    }

    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        // Here it'll trigger a db call if the JWT token is valid (say we are using Eloquent provider)
        return $this->user = $this->provider->retrieveById($payload['sub']);
    }
}

Suggestion

If our JWTGuard provides a customized id() function, for example:

public function id()
{
    if ($this->jwt->setRequest($this->request)->getToken() &&
        ($payload = $this->jwt->check(true)) &&
        $this->validateSubject()
    ) {
        return $payload['sub'];
    }
}

Then we can eliminate the unnecessary db call.

What do you think?