Some apps never ask for a password. You type your email, open your inbox, click the link there, and you're in.
That's a magic link: a login with no password. The server sends a single-use link to your inbox, and that link is what logs you in. Picture a concert ticket a courier drops in your mailbox. Only someone who can open that mailbox holds it, the ticket is valid for a short while, and the door staff tear it the moment you walk in. The staff don't keep a copy of the ticket either, only its fingerprint, so the list on their desk can't get anyone in. In this picture, the mailbox is the email inbox, the ticket is the link with a random token, and the door staff are the server. Tearing the ticket means marking the link as used. The ticket's fingerprint is the token's hash, and the list on the desk is the table in the database.
The flow, from asking for a link to logging in
Siti is at a computer in the school lab. Here is the HTTP conversation in School Portal, exactly what the Lab shows (the token in the Lab is random, so yours differs):
POST /login/magic HTTP/1.1
Host: portal.school.test
{"email": "[email protected]"}
HTTP/1.1 200 OK
{"message": "If that email is registered, a login link is on its way."}
POST /login/magic/verify HTTP/1.1
Host: portal.school.test
{"token": "tpmgXDRJ3orPtbFOFHTJ7hsTekLTOsYF9t7y0VOpiC0"}
HTTP/1.1 200 OK
Set-Cookie: sid=68d8fe15f44bf1c846cb2b4c0fce005b; Path=/; Max-Age=7200; HttpOnly; Secure; SameSite=Lax
{"message": "Logged in", "user": "Siti"}
- The server makes a random token, stores its hash with the
user_idand an expiry time, then sends an email holdinghttps://portal.school.test/login/magic?token=tpmgXDRJ3orPtbFOFHTJ7hsTekLTOsYF9t7y0VOpiC0. The raw token, before hashing, exists only in the email. - That link opens a small page with a Sign in button, and the button sends the token to
POST /login/magic/verify. The server hashes the token, looks up the row, then checks: already used? expired? - If the token is neither used nor expired, the row is marked used, then the server creates a new session, the same as a login in the Session-based Authentication lesson.
Why doesn't the link log the user in right away with the GET? Many office mail filters and chat apps open links automatically to inspect them. If the GET already spends the token, the link is dead before Siti ever clicks it. A page with a button that sends a POST makes sure the person is the one who spends the token, because those automatic checkers don't press buttons.
Making the token: 32 random bytes
This code makes the token, stores its hash in magicLinks (a Map that plays the role of the table), then returns the link for the email:
function base64url(bytes) {
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
async function sha256Hex(text) {
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
}
const MINUTE = 60 * 1000;
const magicLinks = new Map(); // token_hash -> { userId, expiresAt, usedAt }
async function issueLink(user, now) {
const token = base64url(crypto.getRandomValues(new Uint8Array(32))); // 256 random bits
magicLinks.set(await sha256Hex(token), { userId: user.id, expiresAt: now + 15 * MINUTE, usedAt: null });
return `https://portal.school.test/login/magic?token=${token}`; // goes in the email
}
crypto.getRandomValues(new Uint8Array(32)): 32 bytes (256 bits) from a cryptographic random generator (a source of random numbers nobody can predict). Don't useMath.random, and don't build a token out of the email and the time.base64url: Base64 that is safe in a URL:+becomes-,/becomes_, and no=at the end. 32 bytes become 43 characters.sha256Hex: the SHA-256 built into browsers and Node throughcrypto.subtle, giving 64 hex characters. Only this result goes into the table.expiresAt: 15 minutes from now, in milliseconds.
Store the hash, not the token
The token tpmgXDRJ... above has the SHA-256 60646dddaef6c2c0718dd0d3ed7def94bcf04a867cc572f770f5def580b12f15. This is the magic_links table after Siti asks for a link at 07:00:
| token_hash | user_id | expires_at | used_at |
|---|---|---|---|
60646ddd...80b12f15 |
1 | 07:15 | empty |
When a token arrives, the server computes its SHA-256 and looks for the row with that hash. What if the token_hash value itself is sent? The server computes the SHA-256 of that hash, gets d48b5176..., and no row matches. So if School Portal's database leaks, even Siti's unused magic link row can't be used to log in. Logging in takes the raw token, and the raw token exists only in Siti's email.
Why is SHA-256 enough when passwords need a deliberately slow hash (the Password Hashing lesson)? People choose passwords and they can be guessed, so every guess has to be made expensive. This token is 256 random bits, so there is no sensible list of guesses. SHA-256 is also fast and uses no salt, so the same token always gives the same hash. That is why the lookup can go straight through an index (a sorted list that makes database searches fast) on the token_hash column, with no row-by-row checking.
Checking the link: three reasons to refuse
verifyLink gets the token from the Sign in button and the current time (now):
async function verifyLink(token, now) {
const row = magicLinks.get(await sha256Hex(token));
if (!row) return { ok: false, reason: "not_found" };
if (row.usedAt !== null) return { ok: false, reason: "already_used" };
if (now >= row.expiresAt) return { ok: false, reason: "expired" };
row.usedAt = now; // single use: marked before answering
return { ok: true, userId: row.userId };
}
The order: not found first, then already used, then expired. This is a trace from the Lab:
| Time | What happens | Result |
|---|---|---|
| 07:00 | Siti asks for a link, valid until 07:15 | email sent |
| 07:03 | the link is opened | ok: true, new session |
| 07:04 | the same link is opened again | already_used |
| 07:05 | Siti asks for a new link, valid until 07:20 | email sent |
| 07:20 | the second link is opened | expired, because right at the limit it has expired |
| 07:21 | the token_hash value is sent |
not_found |
- Single use: a link that still works after it was used can be used again by anyone who finds it later, in the inbox, the browser history or a forwarded email.
usedAtstops that. - Short life: a link left in an inbox for months is like a spare key nobody remembered to revoke. 15 minutes is enough to open an email.
- The browser gets the same answer for all three refusals:
401with "This login link no longer works. Ask for a new one." The detailed reason goes to the server log.
In the exercise the token is 32 random bytes from crypto.getRandomValues, written as hex (64 characters), and the time is a plain number of milliseconds. issue("[email protected]", 1000) returns a token valid until 1000 + 15 * 60 * 1000, and a valid verify returns { ok: true, email }. The order of checks and the three reasons are the same as in verifyLink above. The difference from a real app: the exercise keeps the token as it is in a Map, while a real app stores only its SHA-256.
Registered or not, the answer is the same
[email protected] is no longer registered: Mrs. Dewi deleted that alumnus account in the first lesson. When he asks for a link, the server answers 200 with exactly the same message it gave Siti. The only difference is inside the server: no new row, no email. If the answers differed, for example "Email not registered", the link request form would become a tool for checking which emails have an account. It is the same principle as the failed-login message in the Password Hashing lesson. Sending an email takes time, so send it through a queue (a list of jobs that run in the background). Then the response time doesn't differ much either.
Opened on another device
Siti asks for the link on the lab computer but opens her email on her phone. The phone is what gets logged in, the device that opened the link, because that is where the Set-Cookie arrives. The lab computer stays logged out. That is on purpose. Suppose the server also logged in the device that asked for the link, just because the link was clicked somewhere else. Then anyone who typed Siti's email on their own device could get in the moment Siti clicked. Want to be logged in on the lab computer? Open the email on that computer.
Strengths and weaknesses
There is no password to forget, leak, or reuse on another site. But the whole account's security rests on the security of the email: anyone who can open Siti's inbox can log in as Siti. For important accounts like Mrs. Dewi's admin account, add a second factor as in the Multi-factor Authentication (MFA) lesson, or use a passkey as in the Passwordless & Passkeys lesson.
In Laravel: signed URLs
In Laravel, the link can be a signed URL (a URL the server signs with APP_KEY):
// routes/web.php: the GET shows the Sign in button, the button POSTs to the same URL
Route::get('/login/magic/{user}', [MagicLinkController::class, 'confirm'])->name('login.magic')->middleware('signed');
Route::post('/login/magic/{user}', [MagicLinkController::class, 'login'])->middleware('signed');
// When Siti asks for a link, and her email is found in the users table
$url = URL::temporarySignedRoute('login.magic', now()->addMinutes(15), ['user' => $user->id]);
Mail::to($user)->queue(new MagicLinkMail($url)); // a Mailable you write
// MagicLinkController@login
if (! Cache::add('magic-used:'.$request->query('signature'), true, now()->addMinutes(15))) {
abort(403, 'This login link was already used.');
}
Auth::login($user);
$request->session()->regenerate();
URL::temporarySignedRoutebuilds a URL likehttps://portal.school.test/login/magic/1?expires=1768176900&signature=....expiresis its time limit in Unix seconds, andsignatureis an HMAC-SHA256 of that URL withAPP_KEY. Change one character and the signature no longer matches.- The
signedmiddleware refuses a URL that was changed or is pastexpireswith403 Invalid signature. - A signed URL doesn't know whether it was already used.
Cache::addonly writes when there is no marker for that signature yet, so the second click getsfalseand is refused. That is what makes it single use. Auth::loginthensession()->regenerate(): a new session, exactly as in the Session-based Authentication lesson. ThePOST /login/magicroute that sends the email gets athrottle(a limit on the number of requests) too, covered in the Rate Limiting for Authentication lesson.
⚠️ Links someone else can use, or that die too early
- Storing the raw token. A database leak then leaks every link that still works. Store only its SHA-256.
- Forgetting to mark it used. The second click must be refused with
already_used, so the used flag must really be written back to the row. - Logging in straight from the
GET. Link checkers in email spend it first. Use a confirmation page and aPOST. - bcrypt for the token, then matching rows one by one. Slow and unnecessary. A random 256-bit token only needs SHA-256, looked up through an index.
TL;DR: Magic link: the user types an email, then the server sends a link holding a random 32-byte token (base64url, 43 characters) to that inbox. The server stores only the token's SHA-256, with user_id, expires_at (15 minutes) and used_at. The link is used through a confirmation page and a POST. The server hashes the incoming token, then refuses in order: not_found, already_used, expired (right at the limit counts as expired). A valid one is marked used first, then gets a new session. The answer to a link request is always the same, whether the email is registered or not. The device that opens the link is the one that logs in. A leaked hash can't be used to log in. The weakness: the account is only as safe as the email. In Laravel: URL::temporarySignedRoute and the signed middleware (a signed URL with a time limit), plus a used marker such as Cache::add, because a signed URL on its own works any number of times until expires.
⚡ Logging in through a link in the inbox
Meaning: A magic link is a login with no password: the server sends a single-use link to the inbox, and that link is what logs you in. The token in the link is 32 random bytes. The server stores only its hash, so a leaked database doesn't leak links that still work.
⚡ Three reasons to refuse
Write:
async function verifyLink(token, now) {
const row = magicLinks.get(await sha256Hex(token));
if (!row) return { ok: false, reason: "not_found" };
if (row.usedAt !== null) return { ok: false, reason: "already_used" };
if (now >= row.expiresAt) return { ok: false, reason: "expired" };
row.usedAt = now; // single use: marked before answering
return { ok: true, userId: row.userId };
}
Guess first: why must the link work only once?
Because a link that still works after it was used can be found later by someone else, in the inbox, the browser history or a forwarded email, and used again.
Meaning: magicLinks is the server's table of links, looked up by the token's SHA-256 (sha256Hex). The order of refusals: not found (not_found), already used (already_used), then expired (expired). A valid link is marked used (usedAt) right before the answer. Its life is short: 15 minutes is enough to open an email.
⚡ Registered or not, the same answer
Meaning: When someone asks for a link for an unregistered email, the server still answers 200 with exactly the same message as for a registered one. The only difference is inside the server: no new row and no email. If the answers differed, the link request form would become a tool for checking which emails have an account.