Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Generate random unique token

I have a table in my database called keys that has this structure:

id | user_id | token_id | token_key

Every time a user logs into my site, I need to generate a new token_id and token_key set for that user. How can I generate a random token for both the token_id and the token_key while keeping the two values unique?

For example, if:

  • token_id is dfbs98641aretwsg,
  • token_key is sdf389dxbf1sdz51fga65dfg74asdf

Meaning:

id | user_id | token_id         | token_key
1  | 1       | dfbs98641aretwsg | sdf389dxbf1sdz51fga65dfg74asdf

There can be no other row in the table with that combination of tokens. How can I do this?

like image 604
user5486944 Avatar asked Oct 25 '15 20:10

user5486944


People also ask

How to create unique token in Laravel?

In terms of generating the tokens, you could use one of Laravel's Helper Functions; str_random() . This will generate a random string of a specified length, e.g str_random(16) will generate a random string of 16 characters (upper case, lower case, and numbers).

What is laravel Sanctum?

Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account.


2 Answers

I'd avoid including an extra package for a case like this one. Something like:

do {
    $token_id = makeRandomToken();
    $token_key = makeRandomTokenKey();
} while (User::where("token_id", "=", $token_id)->where("token_key", "=", $token_key)->first() instanceof User);

...should do. Replace model name with yours, if different from 'User', and use your or suggested functions for creating random strings.

like image 130
Oliver Maksimovic Avatar answered Sep 21 '22 21:09

Oliver Maksimovic


In terms of generating the tokens, you could use one of Laravel's Helper Functions; str_random().

This will generate a random string of a specified length, e.g str_random(16) will generate a random string of 16 characters (upper case, lower case, and numbers).

Depending on how you are using the tokens, do they really need to be completely unique? Given that they will match to a user, or I assume you may be using the token_id and then verifying this against the token_key does it really matter if there is a double up of one of them? - although the chances of this are extremely small!

However, if you do need them to be truly unique you can always use a validator with the unique constraint. Using this package you could also test that the two of them are unique too with unique_with. And then if the validator fails then it generates a new token as needed.

Based off your examples, you would be using str_random(16) for token_id and str_random(30) for the token_key.

like image 21
James Avatar answered Sep 21 '22 21:09

James