Search code examples
phplaravellaravel-sanctum

Why does one need to pass a string in the createToken method?


For creating an access token in Laravel Sanctum, one needs to pass a string inside the createToken method. I find this strange since whatever you pass in gets either hashed using SHA-256 or you can aquire the plain text token.

Why isn't the access token just created based on a random string? It could've easily been done with Str::random(10) for example. I'm not too sure what to pas as the name.


Solution

  • The string you pass to createToken is a token name.

    While you may not need it, there are some use cases where it will be useful.

    For example, if you may have two different types of tokens one for the web and one for a mobile app and each type has a different expiry time, you can then group each type under a certain name like 'web-token' and 'mobile-token'.

    Not everyone need that functionality, but it's good to have it you never know when you're gonna need it.

    If you want to generate a random name automatically, you can simply overwrite the createToken method to generate a random string like so:

    Open app/User.php and paste the following method.

    public function createToken(array $abilities = ['*'])
    {
        $token = $this->tokens()->create([
            'name' => Str::random(10),
            'token' => hash('sha256', $plainTextToken = Str::random(80)),
            'abilities' => $abilities,
        ]);
    
        return new NewAccessToken($token, $token->id.'|'.$plainTextToken);
    }
    

    This is not tested, but it should work.