Is there a specification or recommendations on implementing “one-time authentication” link?

Hello everyone

I’m trying to implement a “magic link” or “one-time login link” functionality

I wonder what a secure way to implement it would be.

The obvious and most simple solution to me seems to be generating a long enough string and storing it in the database.

When the link is opened, the app will just check the value against the database, and verify that it has not expired based on the creation date

But, an alternative way is to use encryption. Seems beneficial because it does not involve the generation of long enough string? As we can encrypt only database identifier which leads to a record of when the login request was made (to check if not expired)

I appreciate any feedback or tips, thanks :pray:

2 Likes

Corresponding tweet for this thread:

Share link for this tweet.

2 Likes

That’s basically what that “long enough string” is, when its long enough and random then you have enough entropy to not worry about it. Just using a UUIDv4 is enough entropy to not worry about it if it expires anywhere in the next thousand years, lol.

Except you encrypt it, which means it’s going to balloon in size to get enough entropy to be worth encrypting, which is going to end up longer in the URL anyway.

3 Likes

If the user has an account then I generally use SecureRandom to generate a random url-safe string then put that in the db associated with the user and an expiry, then in the URL params I will add the user’s ID as well as the generated string, that way the ID must correspond with the string, or it won’t work :023:

There’s an Elixir library for SecureRandom:

iex> SecureRandom.urlsafe_base64
"xYQcVfWuq6THMY_ZVmG0mA"
2 Likes