auth-flow-validation

v2026.09.24

Authentication flow validation between frontend and backend. Covers JWT, OAuth2, token refresh, and session management sync. USE WHEN: user asks about "auth integration", "JWT validation", "token refresh", "401 handling", "authentication flow", "login integration" DO NOT USE FOR: security auditing - use security skills, OAuth provider setup - use authentication skills

GitHub
安装命令
npx skhub add claude-dev-suite/auth-flow-validation
Markdown
SKILL.md

Auth Flow Validation - Quick Reference

When NOT to Use This Skill

  • Security auditing - Use security skills
  • OAuth provider configuration - Use oauth2 skill
  • JWT implementation - Use jwt skill

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: jwt or oauth2 for protocol details.

Auth Flow Overview

┌─────────────────────────────────────────────────────────────────────┐
│                     AUTHENTICATION FLOW                              │
├─────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  Frontend                    Backend                                 │
│  ┌──────────────┐           ┌──────────────┐                        │
│  │ 1. Login     │──────────→│ POST /auth   │                        │
│  │    Form      │           │ /login       │                        │
│  └──────────────┘           └──────┬───────┘                        │
│         ↑                          │                                 │
│         │                          ↓                                 │
│  ┌──────────────┐           ┌──────────────┐                        │
│  │ 2. Store     │←──────────│ Return JWT   │                        │
│  │    Tokens    │           │ + Refresh    │                        │
│  └──────────────┘           └──────────────┘                        │
│         │                                                            │
│         ↓                                                            │
│  ┌──────────────┐           ┌──────────────┐                        │
│  │ 3. API Call  │──────────→│ Validate JWT │                        │
│  │ + Auth Header│           │              │                        │
│  └──────────────┘           └──────┬───────┘                        │
│         ↑                          │                                 │
│         │      401 Unauthorized    │                                 │
│         │←─────────────────────────┤                                 │
│         │                          │                                 │
│         ↓                          │                                 │
│  ┌──────────────┐           ┌──────────────┐                        │
│  │ 4. Refresh   │──────────→│ POST /auth   │                        │
│  │    Token     │           │ /refresh     │                        │
│  └──────────────┘           └──────────────┘                        │
│                                                                      │
└─────────────────────────────────────────────────────────────────────┘

Validation Checklist

Login Flow

StepFrontendBackendValidation
EndpointPOST /auth/loginPOST /auth/loginPath match
Request Body{ email, password }{ email, password }Schema match
Response{ accessToken, refreshToken, user }Same structureType match
Token StoragelocalStorage/httpOnly cookieExpects cookie or headerMethod match
Error ResponseHandle 401, 400Returns structured errorError format

Token Refresh Flow

StepFrontendBackendValidation
Trigger401 response interceptedReturns 401 on expiredConsistent behavior
EndpointPOST /auth/refreshPOST /auth/refreshPath match
RequestrefreshToken in body/cookieExpects same locationMethod match
ResponseNew accessTokenReturns new tokenStructure match
RetryOriginal request retriedAccepts new tokenFlow complete

Common Discrepancies

1. Token Storage Mismatch

// Backend expects: HttpOnly cookie
res.cookie('accessToken', token, {
  httpOnly: true,
  secure: true,
  sameSite: 'strict',
});

// Frontend stores: localStorage (MISMATCH!)
localStorage.setItem('accessToken', response.accessToken);

// Frontend should: Let backend set cookie
// No manual storage needed - cookie sent automatically

2. Authorization Header Format

// Backend expects
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...

// Frontend sends (WRONG)
Authorization: eyJhbGciOiJIUzI1NiIs...  // Missing "Bearer "

// Frontend sends (WRONG)
Authorization: bearer eyJhbGciOiJIUzI1NiIs...  // Wrong case

// Correct frontend implementation
const token = getAccessToken();
fetch('/api/users', {
  headers: {
    'Authorization': `Bearer ${token}`,
  },
});

3. Refresh Token Placement

// Backend expects: Cookie
app.post('/auth/refresh', (req, res) => {
  const refreshToken = req.cookies.refreshToken;  // From cookie
});

// Frontend sends: Body (MISMATCH!)
fetch('/auth/refresh', {
  method: 'POST',
  body: JSON.stringify({ refreshToken }),  // Wrong!
});

// Correct: Cookie sent automatically
fetch('/auth/refresh', {
  method: 'POST',
  credentials: 'include',  // Include cookies
});

4. Token Expiration Handling

// Backend: Token expires after 15 minutes
const token = jwt.sign(payload, secret, { expiresIn: '15m' });

// Frontend: No expiration check (BAD)
function makeAuthenticatedRequest() {
  return fetch('/api/data', {
    headers: { Authorization: `Bearer ${token}` },
  });
}

// Frontend: Check expiration before request (GOOD)
function makeAuthenticatedRequest() {
  const token = getAccessToken();

  if (isTokenExpired(token)) {
    await refreshAccessToken();
  }

  return fetch('/api/data', {
    headers: { Authorization: `Bearer ${getAccessToken()}` },
  });
}

// Helper to check expiration
function isTokenExpired(token: string): boolean {
  const payload = JSON.parse(atob(token.split('.')[1]));
  return payload.exp * 1000 < Date.now();
}

Token Refresh Patterns

Axios Interceptor

import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
});

// Request interceptor - add token
api.interceptors.request.use((config) => {
  const token = getAccessToken();
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Response interceptor - handle 401
api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const originalRequest = error.config;

    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;

      try {
        const newToken = await refreshAccessToken();
        originalRequest.headers.Authorization = `Bearer ${newToken}`;
        return api(originalRequest);
      } catch (refreshError) {
        // Refresh failed - logout user
        logout();
        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  }
);

Fetch with Refresh

async function fetchWithAuth(url: string, options: RequestInit = {}) {
  let token = getAccessToken();

  // Check if token expired
  if (isTokenExpired(token)) {
    token = await refreshAccessToken();
  }

  const response = await fetch(url, {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ${token}`,
    },
  });

  // Handle 401 (token rejected by server)
  if (response.status === 401) {
    token = await refreshAccessToken();

    return fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${token}`,
      },
    });
  }

  return response;
}

React Query Auth

import { QueryClient } from '@tanstack/react-query';

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: (failureCount, error) => {
        // Don't retry on 401
        if (error instanceof Response && error.status === 401) {
          return false;
        }
        return failureCount < 3;
      },
    },
  },
});

// Global error handler
queryClient.setDefaultOptions({
  mutations: {
    onError: (error) => {
      if (error instanceof Response && error.status === 401) {
        // Redirect to login
        window.location.href = '/login';
      }
    },
  },
});

OpenAPI Auth Definition

JWT Bearer

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

paths:
  /users:
    get:
      security:
        - bearerAuth: []
      responses:
        401:
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'

Cookie Auth

components:
  securitySchemes:
    cookieAuth:
      type: apiKey
      in: cookie
      name: accessToken

paths:
  /users:
    get:
      security:
        - cookieAuth: []

Validation Report Template

## Auth Flow Validation Report

### Login Flow
| Check | Status | Details |
|-------|--------|---------|
| Endpoint path | OK | POST /auth/login |
| Request body | OK | { email, password } |
| Response structure | WARNING | Missing `expiresIn` field |
| Token storage | ERROR | Frontend uses localStorage, backend expects cookie |

### Token Refresh Flow
| Check | Status | Details |
|-------|--------|---------|
| Trigger condition | OK | 401 intercepted |
| Refresh endpoint | OK | POST /auth/refresh |
| Token placement | ERROR | Frontend sends in body, backend expects cookie |
| Retry mechanism | OK | Original request retried |

### Recommendations
1. **Critical**: Change token storage to httpOnly cookies
2. **Critical**: Update refresh to use credentials: 'include'
3. **Warning**: Add expiresIn to login response for proactive refresh

Anti-Patterns

Anti-PatternWhy It's BadCorrect Approach
localStorage for tokensXSS vulnerabilityUse httpOnly cookies
No token refreshPoor UX, forced logoutImplement refresh flow
Refresh on every requestPerformanceRefresh on 401 or near expiry
No logout on refresh failSecurity riskClear tokens and redirect
Hardcoded token expiryDrift with backendParse from token or response

Quick Troubleshooting

IssueLikely CauseSolution
401 on loginWrong credentials formatCheck request body schema
401 after refreshRefresh token also expiredRe-authenticate user
Infinite refresh loopNot marking retried requestsAdd retry flag
CORS on auth endpointsMissing credentials configAdd credentials: 'include'
Token not sentAuthorization header formatCheck "Bearer " prefix

Related Skills

发现
标签

此技能尚未发布标签。

版本
最新版本元数据

版本

v2026.09.24

发布时间

2026年9月24日

分类

未分类

许可证

MIT

源路径

skills/integration-validation/auth-flow-validation

默认分支

main

最新提交

9496306

Tree SHA

fe4e2f1