Skip to main content
Fixing the OAuth 2FA Token Collision Bug

Fixing the OAuth 2FA Token Collision Bug

Andrius LukminasAndrius LukminasJanuary 19, 20264 min read104 views

The Bug Report

Users with 2FA enabled were occasionally unable to log in via Google or GitHub OAuth. The error was cryptic:

Unique constraint failed on the constraint: `verification_tokens_token_key`

Root Cause Analysis

Investigation revealed the issue: when creating pending 2FA sessions, we used the user's ID as the token value. If a user tried logging in again before the previous 5-minute session expired, Prisma would fail on the unique constraint.

The Fix

Simple but effective—delete any existing pending tokens before creating a new one:

// Delete any existing pending 2FA tokens for this user
await prisma.verification_tokens.deleteMany({
  where: { token: user.id },
});

// Now create the new pending session
await prisma.verification_tokens.create({
  data: {
    identifier: `2fa_pending:${pendingSessionId}`,
    token: user.id,
    expires,
  },
});

Lessons Learned

  • Unique constraints need careful consideration in multi-step flows
  • OAuth callback paths need the same rigor as regular auth flows
  • Test repeated login attempts, not just happy paths

Related Articles

Comments

0/5000 characters

Comments from guests require moderation.