Prompt

How do I implement passwordless authentication with magic links or OTPs?

Technology / Identity & Access2 observationsLast seen Nov 10, 2026

Latest observation

Nov 10, 2026OpenAI APIWeb search: off

Passwordless authentication with magic links or one-time passwords (OTPs) is usually built as a two-step flow:

  1. User submits an identifier
    Usually an email address or phone number.
  2. Server sends a short-lived, single-use secret
    • Magic link: a signed token embedded in a URL
    • OTP: a short code the user enters back into the app
  3. User verifies the secret
  4. Server creates a session
    • Usually via an HTTP-only session cookie or token

1) Recommended architecture

Magic link flow

  • User enters email
  • Server generates a cryptographically secure token
  • Token is stored hashed in DB/Redis with:
    • user/email
    • expiration time
    • single-use flag
  • Server emails a link like: https://example.com/auth/verify?token=...
  • When clicked:
    • server validates token
    • marks it used
    • creates session
    • redirects user to app

OTP flow

  • User enters email or phone
  • Server generates a 6-digit or 8-digit code
  • Store hashed code with expiry and attempt count
  • Send code via email/SMS
  • User enters code
  • Server verifies it
  • Create session

2) Security requirements

No matter which method you use:

  • Use secure random generation
    • Magic links: at least 128 bits of entropy
    • OTPs: use crypto.randomInt() or equivalent
  • Store tokens/codes hashed, not plaintext
  • Expire quickly
    • Magic links: 10–30 minutes
    • OTPs: 5–10 minutes
  • Single-use only
  • Rate limit requests and verification attempts
  • Prevent account enumeration
    • Return the same response whether or not the account exists
  • Bind token to context if possible
    • optional: device/browser fingerprint, IP range, or user agent
  • Use HTTPS only
  • Use secure cookies
    • HttpOnly, Secure, SameSite=Lax or Strict
  • Invalidate on new request
    • if a new magic link is requested, invalidate previous ones
  • Add anti-abuse protections
    • CAPTCHA, throttling, email reputation checks, SMS fraud controls

3) Magic link implementation pattern

Database schema example

users
- id
- email
- created_at

login_tokens
- id
- user_id
- token_hash
- expires_at
- used_at
- created_at
- request_ip
- user_agent

Generate token

Use a long random token:

import crypto from "crypto";

const token = crypto.randomBytes(32).toString("hex"); // 64-char token
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");

Send link

const link = `https://example.com/auth/verify?token=${token}`;

Verify

  • Hash the incoming token
  • Find matching DB record
  • Check:
    • exists
    • not expired
    • not used
  • Mark used
  • Create session

4) OTP implementation pattern

Generate OTP

import crypto from "crypto";

const otp = crypto.randomInt(100000, 1000000).toString(); // 6 digits

Store hashed OTP

const otpHash = crypto.createHash("sha256").update(otp).digest("hex");

Verification rules

  • Match the hash
  • Enforce expiry
  • Limit attempts, e.g. 5 tries
  • Invalidate after successful use

UX tip

For email OTPs, auto-focus the input and allow paste handling. For SMS, support auto-fill on mobile where possible.


5) Example flow for email magic links

Request login

POST /auth/request-link

  • Input: email
  • Always respond: “If that email exists, we sent a link.”

Verify link

GET /auth/verify?token=...

  • Validate token
  • Create session
  • Redirect to app

6) Example flow for email OTP

Request code

POST /auth/request-otp

  • Input: email
  • Send 6-digit code

Verify code

POST /auth/verify-otp

  • Input: email + code
  • If valid, create session

7) Session management

After successful login, prefer:

  • Server-side session
  • Stored in a secure, HTTP-only cookie

Example cookie settings:

  • HttpOnly: true
  • Secure: true
  • SameSite: Lax
  • Max-Age: session duration

If using JWTs, be careful: storing them in localStorage is less secure. A secure cookie-based session is usually better for web apps.


8) Abuse prevention checklist

  • Rate limit by:
    • IP
    • email/phone
    • device fingerprint if appropriate
  • Cap verification attempts
  • Add cooldown between resend requests
  • Log suspicious behavior
  • Protect against email bombing / SMS flooding
  • Consider CAPTCHA after repeated failures

9) Best practices by channel

Email

  • Good for account recovery and low-friction login
  • Magic links are convenient
  • OTPs are better when users may access the app on a different device than their inbox

SMS

  • Convenient but less secure than email
  • Vulnerable to SIM swap and interception
  • Use only if appropriate for your risk profile

Passkeys

If possible, consider passkeys/WebAuthn as a stronger modern passwordless option. Magic links and OTPs are simpler, but passkeys are more secure and phishing-resistant.


10) Common pitfalls

  • Reusing tokens
  • Storing plaintext codes
  • Long expiry windows
  • Not rate limiting
  • Revealing whether an account exists
  • Putting secrets in logs or analytics
  • Using insecure redirects after verification
  • Letting verification links work indefinitely

11) Minimal implementation outline

  1. User enters email/phone
  2. Generate random token/code
  3. Hash and store it with expiry
  4. Send link/code
  5. Verify token/code on return
  6. Mark it used
  7. Create authenticated session
  8. Redirect user

If you want, I can also give you:

  • a Node.js/Express example
  • a Next.js + Prisma example
  • a Python/FastAPI example
  • or a production-ready schema and API design

Observation history

How did Obsurfable measure this prompt?

Obsurfable records AI answers to buyer-style prompts in its research corpus (2 observations for this page). Metrics are distributions over observations, not a single static ranking.

Which AI systems does Obsurfable collect answers from?

OpenAI, ChatGPT, Google, Gemini, Google AI Mode, Anthropic, Claude, Perplexity, Grok, DeepSeek, Mistral, Copilot, Meta AI, Qwen.

How can brands improve their AEO?

Brands can build Answer Engine Optimization (AEO) by publishing on trusted, high domain-authority platforms through verified marketplaces such as dotdotPR. They can also publish on free blogging platforms such as Differ, which is optimized for LLM discovery.

Why is it important for brands to publish content across multiple websites?

Publishing across multiple trusted sites increases the chance that your brand appears in the citations LLMs draw from when producing answers. Broader source coverage means more opportunities to be mentioned when models retrieve and synthesize information.

Want this interpreted for your brand?

Explorer is the free public corpus. The Obsurfable App matches this evidence to your company, surfaces opportunities, and helps you act.