Choorai
Security-Related Caution

Fixing Auth/Cookie Issues

Logged in but get logged out on refresh? This could be a cookie configuration or CORS-related issue.

TL;DR

1) Set credentials: 'include' 2) Set allow_credentials=True in server CORS 3) Add SameSite=None; Secure attributes to cookies

주의

Cookies not saving / Authentication not persisting

원인

Configuration for cookie transmission is missing when the frontend and backend are on different domains.

해결책
  1. Frontend: Set credentials: 'include' in fetch/axios
  2. Backend: Set allow_credentials=True in CORS, specify exact domain in allow_origins
  3. Cookie: Set SameSite=None, Secure=True (HTTPS required)

Frontend Configuration

Fetch API

api.js
// Send request with cookies included
fetch('https://api.example.com/login', {
  method: 'POST',
  credentials: 'include',  // Important!
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ email, password }),
});

Axios

api.js
import axios from 'axios';

// Global configuration
axios.defaults.withCredentials = true;

// Or per request
axios.post('https://api.example.com/login', data, {
  withCredentials: true  // Important!
});

Backend Configuration

Python FastAPI

main.py
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://your-frontend.com"],  # Cannot use *!
    allow_credentials=True,  # Important!
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.post("/login")
async def login(response: Response):
    # Set cookie
    response.set_cookie(
        key="session",
        value="token-value",
        httponly=True,
        secure=True,        # HTTPS required
        samesite="none",    # Allow cross-site
        max_age=3600 * 24 * 7  # 7 days
    )
    return {"message": "Login successful"}

Node.js Express

server.js
const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors({
  origin: 'https://your-frontend.com',
  credentials: true  // Important!
}));

app.post('/login', (req, res) => {
  res.cookie('session', 'token-value', {
    httpOnly: true,
    secure: true,
    sameSite: 'none',
    maxAge: 7 * 24 * 60 * 60 * 1000  // 7 days
  });
  res.json({ message: 'Login successful' });
});

HTTPS Required!

SameSite=None must be used with Secure=True. This means it only works in HTTPS environments. During development, localhost is exceptionally allowed.

Never do this!

  • Use allow_origins=["*"] together with allow_credentials=True
  • Store sensitive tokens in localStorage
  • Set session cookies without httpOnly

Debugging Methods

  1. Open browser DevTools (F12) → Application → Cookies to check
  2. In the Network tab, verify that the Cookie header is included in request headers
  3. Check if Set-Cookie is present in response headers
  4. Verify there are no CORS-related errors in the Console

Prerequisites

  • You can inspect frontend request code and backend cookie logic.
  • You can verify HTTPS/domain settings in your deployment.
  • You can inspect Set-Cookie and Cookie headers in DevTools.

Validation

  1. Set-Cookie includes expected attributes (HttpOnly, Secure, SameSite).
  2. Subsequent authenticated requests include Cookie header.
  3. Session persists after refresh without CORS regression.

Troubleshooting

  • With SameSite=None, ensure Secure=true and HTTPS are enabled.
  • Check credentials include / withCredentials settings on client requests.
  • Do not combine allow_origins=* with allow_credentials=true.

References

Related Articles

Last updated: February 22, 2026 · Version: v0.0.1

Send Feedback

Opens a new issue page with your message.

Open GitHub Issue