DEV Community

Alim Mohammad
Alim Mohammad

Posted on

Token Types Explained 🔑

1. Access Token

What it is: A short-lived token (usually 15-30 mins) that grants access to protected endpoints.

User logs in → Gets access token → Uses it for 30 mins → Token expires → Must login again

Problem: User has to login again every 30 minutes! 😤

2. Refresh Token (🆕 To Implement)

What it is: A long-lived token (days/weeks) used ONLY to get new access tokens.

Why needed: Better user experience - they stay logged in without re-entering password.

Flow:

┌──────────────────────────────────────────────────────────────────────┐
│ │
│ LOGIN │
│ ────── │
│ User sends email + password │
│ ↓ │
│ Server returns: │
│ • access_token (expires in 30 min) │
│ • refresh_token (expires in 7 days) │
│ │
├──────────────────────────────────────────────────────────────────────┤
│ │
│ USING THE API (for 30 mins) │
│ ─────────────────────────── │
│ User sends: Authorization: Bearer │
│ Server: ✅ Allowed │
│ │
├──────────────────────────────────────────────────────────────────────┤
│ │
│ ACCESS TOKEN EXPIRES (after 30 mins) │
│ ───────────────────────────────────── │
│ User sends: Authorization: Bearer │
│ Server: ❌ 401 Unauthorized - Token expired │
│ │
│ User sends: POST /api/v1/users/refresh │
│ Body: {"refresh_token": "..."} │
│ Server: ✅ Returns NEW access_token (valid for another 30 min) │
│ │
├──────────────────────────────────────────────────────────────────────┤
│ │
│ REFRESH TOKEN EXPIRES (after 7 days) │
│ ───────────────────────────────────── │
│ User must LOGIN AGAIN with email + password │
│ │
└──────────────────────────────────────────────────────────────────────┘

3. Grant Token (OAuth2 Concept)

What it is: Part of the OAuth2 "Authorization Code Flow" - used when logging in via Google, GitHub, etc.

You probably DON'T need this unless you're implementing "Login with Google".

Flow:

User clicks "Login with Google"

Google shows consent page

User approves

Google redirects back with a "grant code"

Your server exchanges grant code for access_token

Top comments (0)