Skip to content

Conversation

@maany
Copy link
Member

@maany maany commented Dec 17, 2025

Summary

This PR fixes a critical authentication issue where users were redirected to the login page after successful authentication in production environments (Kubernetes with Apache proxy), while development mode worked correctly.

Root Cause

The middleware's getToken() function from next-auth/jwt was unable to decrypt the session cookie in production because it requires explicit parameters to match how the token was encrypted:

Parameter Purpose
secret Decryption key
secureCookie Determines cookie prefix (__Secure- for HTTPS)
cookieName Which cookie to read
salt HKDF key derivation salt (must match cookie name)

In development (http://localhost:3000), the cookie name is authjs.session-token and defaults worked. In production (https://...), the cookie name is __Secure-authjs.session-token and explicit parameters are required.

Changes

Authentication middleware (src/middleware.ts):

  • Add explicit getToken() parameters for proper cookie decryption in HTTPS environments
  • Dynamically detect secure cookie mode based on NEXTAUTH_URL
  • Add debug logging for troubleshooting session issues
  • Simplify redirect functions (remove unnecessary async)

Version bump (package.json):

  • Updated version to 39.0.2

Why auth() wrapper wasn't used

The recommended Auth.js v5 pattern using the auth() wrapper failed due to Edge Runtime incompatibility - the import chain pulls in reflect-metadata (uses eval) and node:stream which are not allowed in Edge Runtime where middleware runs.

Test Plan

  • Verify login works in development mode (npm run dev)
  • Verify login works in production behind HTTPS proxy
  • Verify protected routes redirect to login when not authenticated
  • Verify expired Rucio tokens trigger re-authentication

- Add explicit parameters to getToken() for proper cookie decryption
- Dynamically detect secure cookie mode based on NEXTAUTH_URL
- Use correct cookie name and salt for HTTPS deployments
- Add debug logging for troubleshooting session issues

The middleware was failing to decrypt session cookies in production
because getToken() defaults didn't match the __Secure- prefixed
cookie name used in HTTPS environments.
@maany maany merged commit a1bc0ea into master Dec 17, 2025
8 checks passed
@maany maany deleted the middleware_patch branch December 17, 2025 17:51
@maany maany changed the title patch Middleware to decode session cookie in Edge runtime fix(auth): resolve NextAuth session cookie decryption in production Dec 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants