[GH-ISSUE #40] Changing NEXTAUTH_URL behind reverse proxy doesn't work #19

Closed
opened 2026-10-15 13:01:33 +00:00 by bsakaguchi · 14 comments
Owner

Originally created by @shawly on GitHub (Jun 24, 2025).
Original GitHub issue: https://github.com/games-on-whales/wolfmanager/issues/40

I just wanted to try out wolfmanager and set up a compose stack with wolf.
Since I use traefik as reverse proxy, I set the NEXTAUTH_URL to the domain where wolfmanager will be reachable, e.g. NEXTAUTH_URL=https://wolf.example.com

This causes wolfmanager to redirect weirdly which causes my session to be unauthorized even though the login mask accepted my credentials.

When I set NEXTAUTH_URL back to http://localhost:3000 I could login just fine and could view the dashboard etc.
But now when I click on the logout button I get redirected to http://localhost:3000/login.

According to the NextAuth docs, in a production environment NEXTAUTH_URL should be set to the actual domain, like I did.
I also tried setting AUTH_TRUST_HOST=true and NEXTAUTH_TRUST_HOST=true as the docs suggest, but that didn't help either.

Originally created by @shawly on GitHub (Jun 24, 2025). Original GitHub issue: https://github.com/games-on-whales/wolfmanager/issues/40 I just wanted to try out wolfmanager and set up a compose stack with wolf. Since I use traefik as reverse proxy, I set the NEXTAUTH_URL to the domain where wolfmanager will be reachable, e.g. NEXTAUTH_URL=https://wolf.example.com This causes wolfmanager to redirect weirdly which causes my session to be unauthorized even though the login mask accepted my credentials. When I set NEXTAUTH_URL back to http://localhost:3000 I could login just fine and could view the dashboard etc. But now when I click on the logout button I get redirected to http://localhost:3000/login. According to the NextAuth docs, in a production environment NEXTAUTH_URL should be set to the actual domain, like I did. I also tried setting AUTH_TRUST_HOST=true and NEXTAUTH_TRUST_HOST=true [as the docs suggest](https://authjs.dev/getting-started/deployment#auth_trust_host), but that didn't help either.
bsakaguchi 2026-10-15 13:01:33 +00:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@salty2011 commented on GitHub (Jun 26, 2025):

Hey @shawly

Yup I have taken a look and i can see where this has been hardcoded instead of using the nextauth variable.

Thanks will get this sorted asap... also was doing some research and apparently there are some additional things to add as part of the headers so this will work correctly a reverse proxy is in the mix.

As for the other change you had submitted for permission optimization happy for you to merge that branch into 202506.004 where I am staging all changes for the next release before months end.

Was hoping to get SSE working for live updates along with client info. But have ran into some issues due to internal auth

<!-- gh-comment-id:3006646515 --> @salty2011 commented on GitHub (Jun 26, 2025): Hey @shawly Yup I have taken a look and i can see where this has been hardcoded instead of using the nextauth variable. Thanks will get this sorted asap... also was doing some research and apparently there are some additional things to add as part of the headers so this will work correctly a reverse proxy is in the mix. As for the other change you had submitted for permission optimization happy for you to merge that branch into 202506.004 where I am staging all changes for the next release before months end. Was hoping to get SSE working for live updates along with client info. But have ran into some issues due to internal auth
Author
Owner

@salty2011 commented on GitHub (Jul 7, 2025):

hey @shawly

Ive just pushed a new branch I think should resolve the described issues. Are you able give this image a go, you should only need to set the NEXTAUTH_URL to public address.

ghcr.io/games-on-whales/wolfmanager/wolfmanager:fix-issue-40-nextauth-url

If you can let know how that goes and any config instructions for the reverse proxy ill add that info into the documentation as well.

<!-- gh-comment-id:3043190083 --> @salty2011 commented on GitHub (Jul 7, 2025): hey @shawly Ive just pushed a new branch I think should resolve the described issues. Are you able give this image a go, you should only need to set the NEXTAUTH_URL to public address. ghcr.io/games-on-whales/wolfmanager/wolfmanager:fix-issue-40-nextauth-url If you can let know how that goes and any config instructions for the reverse proxy ill add that info into the documentation as well.
Author
Owner

@shawly commented on GitHub (Jul 7, 2025):

Hi @salty2011,

just tested the image with NEXTAUTH_URL set to my public address and the same issue persists.
The log shows this:

[AUTH] auth.ts module loaded at 2025-07-07T06:10:32.269Z
[AUTH] NEXTAUTH_SECRET availability check: hasNextAuthSecret=true, length=128
[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error JWT invalid {
  message: 'JWT invalid',
  stack: 'Error: JWT invalid\n' +
    '    at Object.i (/app/.next/server/chunks/6306.js:25:6932)\n' +
    '    at async _ (/app/.next/server/chunks/6306.js:1:107306)\n' +
    '    at async s (/app/.next/server/chunks/6306.js:25:19586)\n' +
    '    at async p (/app/.next/server/app/api/auth/session/route.js:1:1878)\n' +
    '    at async /app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:38411\n' +
    '    at async e_.execute (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:27880)\n' +
    '    at async e_.handle (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:39943)\n' +
    '    at async doRender (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1366:42)\n' +
    '    at async cacheEntry.responseCache.get.routeKind (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1588:28)\n' +
    '    at async NextNodeServer.renderToResponseWithComponentsImpl (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1496:28)',
  name: 'Error'
}
[AUTH] auth.ts module loaded at 2025-07-07T06:10:32.402Z

I made sure to clean out my session storage and cookies before trying.
I also tried setting the AUTH_TRUST_HOST env var to no avail. Setting NEXT_AUTH_URL back to http://localhost:3000 made it work again.

<!-- gh-comment-id:3043604356 --> @shawly commented on GitHub (Jul 7, 2025): Hi @salty2011, just tested the image with NEXTAUTH_URL set to my public address and the same issue persists. The log shows this: ``` [AUTH] auth.ts module loaded at 2025-07-07T06:10:32.269Z [AUTH] NEXTAUTH_SECRET availability check: hasNextAuthSecret=true, length=128 [next-auth][error][JWT_SESSION_ERROR] https://next-auth.js.org/errors#jwt_session_error JWT invalid { message: 'JWT invalid', stack: 'Error: JWT invalid\n' + ' at Object.i (/app/.next/server/chunks/6306.js:25:6932)\n' + ' at async _ (/app/.next/server/chunks/6306.js:1:107306)\n' + ' at async s (/app/.next/server/chunks/6306.js:25:19586)\n' + ' at async p (/app/.next/server/app/api/auth/session/route.js:1:1878)\n' + ' at async /app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:38411\n' + ' at async e_.execute (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:27880)\n' + ' at async e_.handle (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:39943)\n' + ' at async doRender (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1366:42)\n' + ' at async cacheEntry.responseCache.get.routeKind (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1588:28)\n' + ' at async NextNodeServer.renderToResponseWithComponentsImpl (/app/node_modules/.pnpm/next@14.2.25_react-dom@18.3.1_react@18.3.1__react@18.3.1/node_modules/next/dist/server/base-server.js:1496:28)', name: 'Error' } [AUTH] auth.ts module loaded at 2025-07-07T06:10:32.402Z ``` I made sure to clean out my session storage and cookies before trying. I also tried setting the AUTH_TRUST_HOST env var to no avail. Setting NEXT_AUTH_URL back to http://localhost:3000 made it work again.
Author
Owner

@salty2011 commented on GitHub (Jul 7, 2025):

hey @shawly

Just confirming the testing was done with this image https://github.com/games-on-whales/wolfmanager/releases/tag/preview-202506.004

Oh another thing you may want to try doing a clean state as part of SSE implementation I changed how secrets are auto-generated. would just need wolfmanager.db and .env.local are removed to allow them to regenerate.

<!-- gh-comment-id:3043670792 --> @salty2011 commented on GitHub (Jul 7, 2025): hey @shawly Just confirming the testing was done with this image https://github.com/games-on-whales/wolfmanager/releases/tag/preview-202506.004 Oh another thing you may want to try doing a clean state as part of SSE implementation I changed how secrets are auto-generated. would just need wolfmanager.db and .env.local are removed to allow them to regenerate.
Author
Owner

@shawly commented on GitHub (Jul 7, 2025):

I now also tested ghcr.io/games-on-whales/wolfmanager/wolfmanager:preview-202506.004 and I also cleaned the whole config folder to have a clean slate and the issue still persists.
On the first start I log in with admin:admin then I am greeted with this screen:

Image

When I click the Log in button there, I am redirected to the /first-time-setup route where I can set a new password for the admin account which does work. Afterwards when I login with my new password I constantly land on the authentication required page like in the screenshot, instead of the dashboard.

<!-- gh-comment-id:3043843160 --> @shawly commented on GitHub (Jul 7, 2025): I now also tested ghcr.io/games-on-whales/wolfmanager/wolfmanager:preview-202506.004 and I also cleaned the whole config folder to have a clean slate and the issue still persists. On the first start I log in with admin:admin then I am greeted with this screen: <img width="670" height="477" alt="Image" src="https://github.com/user-attachments/assets/4de77b60-960b-458c-8af3-a9e0e26f82de" /> When I click the Log in button there, I am redirected to the /first-time-setup route where I can set a new password for the admin account which does work. Afterwards when I login with my new password I constantly land on the authentication required page like in the screenshot, instead of the dashboard.
Author
Owner

@salty2011 commented on GitHub (Jul 7, 2025):

🔍 Enhanced JWT Debugging Implemented

I've added comprehensive JWT debugging capabilities to help identify the root cause of the NextAuth reverse proxy JWT validation issue.

🚀 Changes Made

Branch: fix/issue-40-nextauth-url
Commit: ad3351b

  1. New JWT Debug Utility (src/lib/debug/jwt-debug.ts)

    • Tracks URL context during JWT generation vs validation
    • Monitors reverse proxy headers (x-forwarded-*)
    • Analyzes cookie configuration mismatches
    • Logs comprehensive environment state
  2. Enhanced Auth Configuration (src/lib/auth.ts)

    • JWT generation logging with full context
    • Validation failure tracking with detailed analysis
    • URL mismatch detection during authentication flow
  3. Enhanced Middleware (src/middleware.ts)

    • Request header analysis for reverse proxy detection
    • Cookie clearing for both secure and insecure variants
    • Comprehensive JWT validation context logging

🔧 Testing Instructions

  1. Deploy the updated code from the fix/issue-40-nextauth-url branch
  2. Monitor your application logs for these specific patterns:

For URL Context Mismatch (Most Likely Cause):

"JWT_DEBUG: Token generation context" - Check urlContext.externalBaseUrl
"JWT_DEBUG: Token validation context" - Compare with generation URL
"JWT_DEBUG: URL context mismatch detected" - Definitive proof of mismatch
"sessionTokenName" - Check cookie naming consistency
"expectedCookieNames" - Verify browser cookie availability
"cookieSecure" - Validate SSL termination handling

🎯 What to Look For

The logs will show:

  • Environment Variables: NEXTAUTH_URL, NEXTAUTH_SECRET status
  • URL Context: External vs internal base URLs
  • Reverse Proxy Headers: x-forwarded-proto, x-forwarded-host, etc.
  • Cookie Configuration: Secure vs insecure cookie naming
  • Validation Failures: Detailed error context

📋 Next Steps

  1. Deploy and test the enhanced debugging version
  2. Share the JWT_DEBUG log entries when the issue occurs
  3. Check your reverse proxy configuration for:
    • Proper header forwarding (x-forwarded-proto, x-forwarded-host)
    • SSL termination settings
    • NEXTAUTH_URL environment variable matching your public domain

🔧 Potential Quick Fixes

Based on the analysis, try these if the debugging confirms by adding these environment variables to the wolfmanager compose:

For URL Context Mismatch:

# Set NEXTAUTH_URL to match your reverse proxy public URL
NEXTAUTH_URL="https://your-public-domain.com"

For Cookie Security Issues:

# If SSL termination occurs at reverse proxy
INSECURE_COOKIES_IN_PRODUCTION="true"

Please test this enhanced debugging version and share the JWT_DEBUG log entries when you encounter the "JWT invalid" error. This will help us pinpoint the exact cause and provide a targeted fix.

<!-- gh-comment-id:3043993510 --> @salty2011 commented on GitHub (Jul 7, 2025): ## 🔍 Enhanced JWT Debugging Implemented I've added comprehensive JWT debugging capabilities to help identify the root cause of the NextAuth reverse proxy JWT validation issue. ### 🚀 Changes Made **Branch**: `fix/issue-40-nextauth-url` **Commit**: `ad3351b` 1. **New JWT Debug Utility** (`src/lib/debug/jwt-debug.ts`) - Tracks URL context during JWT generation vs validation - Monitors reverse proxy headers (`x-forwarded-*`) - Analyzes cookie configuration mismatches - Logs comprehensive environment state 2. **Enhanced Auth Configuration** (`src/lib/auth.ts`) - JWT generation logging with full context - Validation failure tracking with detailed analysis - URL mismatch detection during authentication flow 3. **Enhanced Middleware** (`src/middleware.ts`) - Request header analysis for reverse proxy detection - Cookie clearing for both secure and insecure variants - Comprehensive JWT validation context logging ### 🔧 Testing Instructions 1. **Deploy the updated code** from the `fix/issue-40-nextauth-url` branch 2. **Monitor your application logs** for these specific patterns: #### For URL Context Mismatch (Most Likely Cause): ``` "JWT_DEBUG: Token generation context" - Check urlContext.externalBaseUrl "JWT_DEBUG: Token validation context" - Compare with generation URL "JWT_DEBUG: URL context mismatch detected" - Definitive proof of mismatch ``` #### For Cookie Configuration Issues: ``` "sessionTokenName" - Check cookie naming consistency "expectedCookieNames" - Verify browser cookie availability "cookieSecure" - Validate SSL termination handling ``` ### 🎯 What to Look For The logs will show: - **Environment Variables**: NEXTAUTH_URL, NEXTAUTH_SECRET status - **URL Context**: External vs internal base URLs - **Reverse Proxy Headers**: x-forwarded-proto, x-forwarded-host, etc. - **Cookie Configuration**: Secure vs insecure cookie naming - **Validation Failures**: Detailed error context ### 📋 Next Steps 1. **Deploy and test** the enhanced debugging version 2. **Share the JWT_DEBUG log entries** when the issue occurs 3. **Check your reverse proxy configuration** for: - Proper header forwarding (`x-forwarded-proto`, `x-forwarded-host`) - SSL termination settings - NEXTAUTH_URL environment variable matching your public domain ### 🔧 Potential Quick Fixes Based on the analysis, try these if the debugging confirms by adding these environment variables to the wolfmanager compose: **For URL Context Mismatch**: ```bash # Set NEXTAUTH_URL to match your reverse proxy public URL NEXTAUTH_URL="https://your-public-domain.com" ``` **For Cookie Security Issues**: ```bash # If SSL termination occurs at reverse proxy INSECURE_COOKIES_IN_PRODUCTION="true" ``` Please test this enhanced debugging version and share the JWT_DEBUG log entries when you encounter the "JWT invalid" error. This will help us pinpoint the exact cause and provide a targeted fix.
Author
Owner

@salty2011 commented on GitHub (Jul 7, 2025):

@shawly > lol I was testing the new github integration with the AI issue management. However the images is currently building.

When its completed building youll need to force update the image. Then proceed with the above testing steps.

Cause i dont have a reverse proxy setup in my environment at the moment will need as much detail as you can give

I think the issue is related to mismatch of url in the cookies. The cookie should have the public url but i think it may be ending up with the localhost address.

Another test to try is confirm how this is working without the reverse proxy / local. From what i am reading there maybe some additional things I need to do to support reverse proxy.

<!-- gh-comment-id:3044004137 --> @salty2011 commented on GitHub (Jul 7, 2025): @shawly > lol I was testing the new github integration with the AI issue management. However the images is currently building. When its completed building youll need to force update the image. Then proceed with the above testing steps. Cause i dont have a reverse proxy setup in my environment at the moment will need as much detail as you can give I think the issue is related to mismatch of url in the cookies. The cookie should have the public url but i think it may be ending up with the localhost address. Another test to try is confirm how this is working without the reverse proxy / local. From what i am reading there maybe some additional things I need to do to support reverse proxy.
Author
Owner

@shawly commented on GitHub (Jul 7, 2025):

wolfman.log

Here's the log, looking at the cookie it seems the domain is the public one not the localhost address.

<!-- gh-comment-id:3044606930 --> @shawly commented on GitHub (Jul 7, 2025): [wolfman.log](https://github.com/user-attachments/files/21101595/wolfman.log) Here's the log, looking at the cookie it seems the domain is the public one not the localhost address.
Author
Owner

@salty2011 commented on GitHub (Jul 9, 2025):

I've analyzed the JWT debugging logs you provided, and I found the exact root cause of the issue!

The logs clearly show a cookie name mismatch:

What NextAuth expects (production with secure cookies):

"sessionTokenName": "__Secure-next-auth.session-token"

What the browser is actually sending:

next-auth.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0...

🔧 The Root Cause

NextAuth is running in production mode with SSL-aware settings, so it's expecting secure cookies with the __Secure- prefix. However, because your SSL termination happens at the reverse proxy level (Traefik), NextAuth should be configured to use non-secure cookies internally.

✅ The Fix

Add this environment variable to your wolfmanager service in docker-compose:

services:
  wolfmanager:
    environment:
      - NEXTAUTH_URL=https://wolf.example.com
      - INSECURE_COOKIES_IN_PRODUCTION=true  # <- Add this line
      # ... your other environment variables

📋 What This Does

Setting INSECURE_COOKIES_IN_PRODUCTION=true tells NextAuth:

  • Use next-auth.session-token instead of __Secure-next-auth.session-token
  • Don't require the Secure flag on cookies (since SSL termination is handled by reverse proxy)
  • Still maintain security through HTTPS at the reverse proxy level

🎯 Why This Happens

This is a common reverse proxy configuration issue:

  1. Traefik handles SSL termination (HTTPS → HTTP)
  2. NextAuth sees the internal HTTP connection and sets secure cookie expectations
  3. Browser sends cookies with public HTTPS domain but without secure prefixes
  4. Cookie name mismatch causes JWT validation to fail

🚀 Next Steps

  1. Add the environment variable to your docker-compose
  2. Restart the wolfmanager container
  3. Clear your browser cookies for the domain
  4. Test the login flow again

This should resolve the JWT validation issue completely. The debugging logs show everything else is configured correctly - URL contexts match perfectly, reverse proxy headers are forwarded properly, it's just the cookie security configuration that needs adjustment.

Let me know if this fixes the issue!

<!-- gh-comment-id:3050908201 --> @salty2011 commented on GitHub (Jul 9, 2025): ## 🔍 Root Cause Identified: Cookie Name Mismatch I've analyzed the JWT debugging logs you provided, and I found the **exact root cause** of the issue! ### ❌ The Problem: Cookie Security Mismatch The logs clearly show a **cookie name mismatch**: **What NextAuth expects (production with secure cookies):** ```json "sessionTokenName": "__Secure-next-auth.session-token" ``` **What the browser is actually sending:** ``` next-auth.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0... ``` ### 🔧 The Root Cause NextAuth is running in **production mode** with **SSL-aware settings**, so it's expecting secure cookies with the `__Secure-` prefix. However, because your **SSL termination happens at the reverse proxy level** (Traefik), NextAuth should be configured to use non-secure cookies internally. ### ✅ The Fix Add this environment variable to your `wolfmanager` service in docker-compose: ```yaml services: wolfmanager: environment: - NEXTAUTH_URL=https://wolf.example.com - INSECURE_COOKIES_IN_PRODUCTION=true # <- Add this line # ... your other environment variables ``` ### 📋 What This Does Setting `INSECURE_COOKIES_IN_PRODUCTION=true` tells NextAuth: - Use `next-auth.session-token` instead of `__Secure-next-auth.session-token` - Don't require the `Secure` flag on cookies (since SSL termination is handled by reverse proxy) - Still maintain security through HTTPS at the reverse proxy level ### 🎯 Why This Happens This is a **common reverse proxy configuration issue**: 1. **Traefik handles SSL termination** (HTTPS → HTTP) 2. **NextAuth sees the internal HTTP connection** and sets secure cookie expectations 3. **Browser sends cookies with public HTTPS domain** but without secure prefixes 4. **Cookie name mismatch** causes JWT validation to fail ### 🚀 Next Steps 1. **Add the environment variable** to your docker-compose 2. **Restart the wolfmanager container** 3. **Clear your browser cookies** for the domain 4. **Test the login flow** again This should resolve the JWT validation issue completely. The debugging logs show everything else is configured correctly - URL contexts match perfectly, reverse proxy headers are forwarded properly, it's just the cookie security configuration that needs adjustment. Let me know if this fixes the issue!
Author
Owner

@salty2011 commented on GitHub (Jul 9, 2025):

Hey @shawly

can you please retest with the aforementioned "INSECURE_COOKIES_IN_PRODUCTION=true" environment variable and confirm if this resolves the issue.

Would be keen to see the log either way. Assuming this works.

<!-- gh-comment-id:3050915654 --> @salty2011 commented on GitHub (Jul 9, 2025): Hey @shawly can you please retest with the aforementioned "INSECURE_COOKIES_IN_PRODUCTION=true" environment variable and confirm if this resolves the issue. Would be keen to see the log either way. Assuming this works.
Author
Owner

@salty2011 commented on GitHub (Jul 11, 2025):

✅ Issue Resolved - Automatic Reverse Proxy Detection Implemented

🎯 Root Cause Identified

The issue was caused by a NextAuth cookie security configuration mismatch when running behind reverse proxies:

  • Production Environment: NextAuth defaults to secure cookies (__Secure-next-auth.session-token)
  • Reverse Proxy Setup: SSL termination at proxy level (Traefik, nginx, etc.)
  • Cookie Mismatch: System expected secure cookies but received non-secure cookies
  • Result: JWT validation failures and authentication loops

🚀 Solution Implemented

Automatic Reverse Proxy Detection

  • New Module: src/lib/auth/reverse-proxy-detection.ts
  • Smart Detection: Automatically detects common reverse proxy headers:
    • x-forwarded-for, x-forwarded-host, x-forwarded-proto
    • x-real-ip, cf-connecting-ip (Cloudflare)
    • x-amzn-trace-id (AWS ALB)
  • Container Awareness: Detects Docker/Kubernetes environments
  • URL Analysis: Checks for external URLs vs localhost patterns
  • Request-Aware: Cookie security determined per request based on detected proxy headers
  • Automatic Switching:
    • Secure cookies for direct HTTPS deployments
    • Insecure cookies for reverse proxy deployments (HTTPS maintained at proxy level)
  • Zero Configuration: Works out-of-the-box for most reverse proxy setups

Enhanced Debugging & Error Handling

  • Comprehensive JWT debugging with reverse proxy detection context
  • Graceful handling of JWT decode errors during configuration transitions
  • Improved logging for troubleshooting reverse proxy issues

✅ Testing Results

Scenario Authentication Cookie Type Status
Direct HTTPS ✅ Working Secure cookies ✅ Tested
Traefik Proxy ✅ Working Insecure cookies ✅ Tested

🔧 Configuration Options

Manual Override (Optional)

environment:
  - INSECURE_COOKIES_IN_PRODUCTION=true          # Force insecure cookies
  - INSECURE_COOKIES_IN_PRODUCTION=force-secure  # Force secure cookies

📋 Key Benefits

  1. 🔧 Zero Configuration: Works automatically for most reverse proxy setups
  2. 🛡️ Security Maintained: HTTPS security preserved at reverse proxy level
  3. 🔄 Universal Compatibility: Supports Traefik, nginx, Cloudflare, AWS ALB, etc.
  4. 📦 Container Ready: Handles Docker, Kubernetes, and direct deployments
  5. 🔄 Backward Compatible: Existing deployments continue to work
  6. 🐛 Enhanced Debugging: Clear identification of proxy configuration issues

🎯 Resolution Summary

  • ✅ Authentication behind reverse proxies now works seamlessly
  • ✅ Automatic detection handles various proxy scenarios
  • ✅ Enhanced error handling prevents JWT decode crashes
  • ✅ Comprehensive testing completed for proxy and non-proxy scenarios

@shawly This should resolve your Traefik reverse proxy authentication issues. The system now automatically detects when it's running behind a reverse proxy and configures cookies appropriately. Please test and let us know if you encounter any issues!

Commit: 6966225

<!-- gh-comment-id:3062530445 --> @salty2011 commented on GitHub (Jul 11, 2025): ## ✅ Issue Resolved - Automatic Reverse Proxy Detection Implemented ### 🎯 **Root Cause Identified** The issue was caused by a **NextAuth cookie security configuration mismatch** when running behind reverse proxies: - **Production Environment**: NextAuth defaults to secure cookies (`__Secure-next-auth.session-token`) - **Reverse Proxy Setup**: SSL termination at proxy level (Traefik, nginx, etc.) - **Cookie Mismatch**: System expected secure cookies but received non-secure cookies - **Result**: JWT validation failures and authentication loops ### 🚀 **Solution Implemented** #### **Automatic Reverse Proxy Detection** - **New Module**: `src/lib/auth/reverse-proxy-detection.ts` - **Smart Detection**: Automatically detects common reverse proxy headers: - `x-forwarded-for`, `x-forwarded-host`, `x-forwarded-proto` - `x-real-ip`, `cf-connecting-ip` (Cloudflare) - `x-amzn-trace-id` (AWS ALB) - **Container Awareness**: Detects Docker/Kubernetes environments - **URL Analysis**: Checks for external URLs vs localhost patterns #### **Dynamic Cookie Configuration** - **Request-Aware**: Cookie security determined per request based on detected proxy headers - **Automatic Switching**: - **Secure cookies** for direct HTTPS deployments - **Insecure cookies** for reverse proxy deployments (HTTPS maintained at proxy level) - **Zero Configuration**: Works out-of-the-box for most reverse proxy setups #### **Enhanced Debugging & Error Handling** - **Comprehensive JWT debugging** with reverse proxy detection context - **Graceful handling** of JWT decode errors during configuration transitions - **Improved logging** for troubleshooting reverse proxy issues ### ✅ **Testing Results** | Scenario | Authentication | Cookie Type | Status | |----------|----------------|-------------|--------| | **Direct HTTPS** | ✅ Working | Secure cookies | ✅ Tested | | **Traefik Proxy** | ✅ Working | Insecure cookies | ✅ Tested | ### 🔧 **Configuration Options** #### **Manual Override (Optional)** ```yaml environment: - INSECURE_COOKIES_IN_PRODUCTION=true # Force insecure cookies - INSECURE_COOKIES_IN_PRODUCTION=force-secure # Force secure cookies ``` ### 📋 **Key Benefits** 1. **🔧 Zero Configuration**: Works automatically for most reverse proxy setups 2. **🛡️ Security Maintained**: HTTPS security preserved at reverse proxy level 3. **🔄 Universal Compatibility**: Supports Traefik, nginx, Cloudflare, AWS ALB, etc. 4. **📦 Container Ready**: Handles Docker, Kubernetes, and direct deployments 5. **🔄 Backward Compatible**: Existing deployments continue to work 6. **🐛 Enhanced Debugging**: Clear identification of proxy configuration issues ### 🎯 **Resolution Summary** - ✅ **Authentication behind reverse proxies now works seamlessly** - ✅ **Automatic detection handles various proxy scenarios** - ✅ **Enhanced error handling prevents JWT decode crashes** - ✅ **Comprehensive testing completed for proxy and non-proxy scenarios** @shawly This should resolve your Traefik reverse proxy authentication issues. The system now automatically detects when it's running behind a reverse proxy and configures cookies appropriately. Please test and let us know if you encounter any issues! **Commit**: [`6966225`](https://github.com/games-on-whales/wolfmanager/commit/6966225)
Author
Owner

@shawly commented on GitHub (Jul 12, 2025):

Awesome thanks! Works with AUTH_TRUST_HOST=true and my domain for the NEXTAUTH_URL perfectly fine now!

<!-- gh-comment-id:3064975664 --> @shawly commented on GitHub (Jul 12, 2025): Awesome thanks! Works with AUTH_TRUST_HOST=true and my domain for the NEXTAUTH_URL perfectly fine now!
Author
Owner

@salty2011 commented on GitHub (Jul 12, 2025):

@shawly so you needed the AUTH_TRUST_HOST before it worked?

Curious in my testing that wasn't needed but the hostname i was using was http://localhost/

Out of interest does having that set work even without reverse proxy and just using IP?

Asking cause I could just build that variable into the container image so it's not required to be set

<!-- gh-comment-id:3065301225 --> @salty2011 commented on GitHub (Jul 12, 2025): @shawly so you needed the AUTH_TRUST_HOST before it worked? Curious in my testing that wasn't needed but the hostname i was using was http://localhost/ Out of interest does having that set work even without reverse proxy and just using IP? Asking cause I could just build that variable into the container image so it's not required to be set
Author
Owner

@shawly commented on GitHub (Jul 13, 2025):

I just tested again and AUTH_TRUST_HOST isn't necessary at all. Dunno what went wrong yesterday without this var.

<!-- gh-comment-id:3066624683 --> @shawly commented on GitHub (Jul 13, 2025): I just tested again and AUTH_TRUST_HOST isn't necessary at all. Dunno what went wrong yesterday without this var.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
games-on-whales/wolfmanager#19
No description provided.