givebutter/laravel-keyable

Hashing the API token (like Laravel Sanctum) before storing it in the database

mwllgr opened this issue · 1 comments

Hello,

because the tokens are pretty much passwords, Laravel Sanctum hashes tokens before saving them to the database in the following format: <id>|<token> - the ID is there for finding the token faster (by primary key lookup).

Here's their implementation for creating a new token, as seen in HasApiTokens.php (line 46)

    public function createToken(string $name, array $abilities = ['*'], DateTimeInterface $expiresAt = null)
    {
        $token = $this->tokens()->create([
            'name' => $name,
            'token' => hash('sha256', $plainTextToken = Str::random(40)),
            'abilities' => $abilities,
            'expires_at' => $expiresAt,
        ]);

        return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
    }

... and here's the way they check it in PersonalAccessToken.php (line 58):

public static function findToken($token)
    {
        if (strpos($token, '|') === false) {
            return static::where('token', hash('sha256', $token))->first();
        }

        [$id, $token] = explode('|', $token, 2);

        if ($instance = static::find($id)) {
            return hash_equals($instance->token, hash('sha256', $token)) ? $instance : null;
        }
    }

I think it'd be a great idea for laravel-keyable to do the same thing. The user would receive a plainTextToken which can only be displayed once.

This will be added in the next release shortly, thanks for the suggestion.