Home > Net >  How to generate an access token in Laravel 9 without using Sanctum or Passport
How to generate an access token in Laravel 9 without using Sanctum or Passport

Time:04-21

I want to implement an API token-based authentication system without using Sanctum or Passport. How can I generate access tokens? Can I just generate a random string?

CodePudding user response:

To start off: I would generally use Laravel's first-party packages whenever possible since they're battle-tested, in this case Laravel Sanctum sounds like the best choice.

But if you have to create your own implementation, yes you can simply generate a random string and store that in the database connected to a specific user. In fact, that's what Sanctum does:

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

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

Source: https://github.com/laravel/sanctum/blob/v2.15.1/src/HasApiTokens.php#L44-L53

Here it generates a random string and saves a hash in the database. The string is hashed so that no one has access to the token except the user (not even you).

CodePudding user response:

If you want to setup your own authentication system, you need to be comfortable with important security concepts like OAuth2, encryption... If it is not the case, it is highly recommanded to use one of scaffolding solutions provided by Laravel to meet your need. Don't hesitate to ask questions about thoses frameworks if you have problems.

Otherwise, if you really want to make auth system yourself, you can use tymondesigns/jwt-auth library to generate auth token.

Good luck !

  • Related