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