1

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?

2 Answers2

3

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).

Thomas
  • 8,426
  • 1
  • 25
  • 49
  • I know it's late but I have a question: What is the value of `$token->getKey()`? Is it the new token id value? – Abdulwahab Almestekawy May 02 '22 at 15:07
  • Yes, `$model->getKey()` returns the model's primary key value (which doesn't have to be called `id`). – Thomas May 02 '22 at 16:04
  • The `$token->getKey()` part is not encrypted? Then why is it appended to the plainTextToken? Is the hashed value of `Str::random(40)` always guaranteed to be unique? – Abdulwahab Almestekawy May 02 '22 at 20:53
  • The key is added [for improved performance](https://stackoverflow.com/questions/69083418/laravel-sanctum-remove-database-id-from-generated-token/71952539#71952539). The string is technically not guaranteed to be unique, but the likelihood of a duplicate is less than one in a trillion. – Thomas May 03 '22 at 07:28
2

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 !

  • Maybe you could edit or add an additional link because tymon's original "was not being updated for long" according to that team who forked and updated it with more features: https://github.com/PHP-Open-Source-Saver/jwt-auth I've worked with it and it's doing fine (at least from that point when I did it). – Thielicious Aug 26 '22 at 14:34