Debugging OAuth Redirect Loops Caused by Oversized HTTP Cookies

Debugging OAuth Redirect Loops Caused by Oversized HTTP Cookies

Last week, we spent almost four hours tracking down a login bug that made zero sense on paper.Our dashboard users signing in with Google or Discord were getting thrown into an infinite redirect loop. They would hit sign in, pick their Google account, authorize it, watch the screen flash for a second, and then land right back on the empty login form.No error message. No red toast. No failed requests in Chrome's network tab. Nothing in the console either.Meanwhile, plain old email-and-password logins worked perfectly. Same database, same API server, same users. If an account logged in with a password, it went straight to the dashboard. If that exact same account clicked "Sign in with Google", it got kicked right back to square one.It turned out we hit a classic browser quirk from RFC 6265 that almost nobody thinks about anymore: the hard 4KB limit on HTTP cookies.To explain why this happened, you have to look at how we split our frontend and backend. The client dashboard runs on one subdomain, and the core API runs on another.When someone signs in with an email and password, the frontend just fires an asynchronous POST request to our auth endpoint. The API checks the credentials, returns a 200 with the user profile and session data right in the JSON response body, and the frontend JavaScript saves that into localStorage and routes to the dashboard.That flow never touches cookies at all.OAuth can't do that because the initial handoff isn't an in-page fetch request. The user gets bounced to Google's consent screen on google.com, and Google bounces them back to our API callback route on our API subdomain.Because that handoff happens at the HTTP level through a 302 redirect, the backend can't just write to localStorage in the user's browser. It has to transfer the session over to the frontend subdomain somehow. So our callback handler set a cookie on the shared parent domain, then fired a 302 redirect to the dashboard URL.Once the dashboard loaded, our React auth provider checked localStorage first. Naturally, it was empty because the user just arrived from Google. So it fell back to checking document.cookie.If it found the auth cookie, it parsed the user data, synced it to localStorage, and loaded the dashboard. If neither existed, the router assumed the user was an unauthenticated stranger and sent them back to the login screen.During initial development, this worked every single time. We created test accounts, clicked through OAuth, and landed on the dashboard without an issue.The bug only showed up when we started testing with older, heavily used accounts.When one of us tried to log in with an account we had been using for weeks across multiple laptops and phones, the redirect loop kicked in immediately.At first we thought it was a SameSite cookie issue. Chrome has been pretty aggressive lately with cross-site cookies, so we figured SameSite=Lax might be dropping our cookie during the top-level GET redirect from Google.But we checked our flags, and we were already using SameSite=Lax, Secure, and an explicit parent domain. That should have been completely fine under modern browser specs.Then we thought we might have a race condition in our frontend code. We had an event listener in the login view listening for window focus events to catch popups, so we wondered if the tab was gaining focus mid-redirect and wiping state.We removed that listener, tested again, and the loop was still there.Eventually we opened Chrome DevTools, turned on "Preserve log" in the Network tab, and watched the whole redirect chain step by step.The 302 response from our callback endpoint was sitting right there. The Set-Cookie header was clearly visible in the response headers. The server was definitely sending it down.But when we looked at the Application tab on the dashboard page right after the redirect finished, document.cookie was completely blank.The server sent the header. The browser got the response. But Chrome just ignored the cookie entirely.We copied the raw Set-Cookie header out of the network tab, pasted it into a terminal, and checked its byte count.It was 6,320 bytes long.That was the mystery solved.RFC 6265 Section 6.1 explicitly says browsers only have to support cookies up to 4,096 bytes per cookie. That includes the name, the value, and all the attributes like Path and Domain.If a server tries to set a cookie larger than 4KB, the browser's networking layer doesn't print an error in the console or warn you in DevTools. It just discards the cookie silently and goes on with its day.So why was our cookie over 6KB?It came down to two things stacking up.First, our backend was trying to be convenient. Instead of just saving a session ID in the cookie and making the frontend fetch the profile on load, the callback endpoint serialized the entire database user object into the cookie value.That user record had an array called sessions. Every time a user logged in, our database pushed an entry tracking their device, IP, user-agent string, and login time.On a brand new test account with one session, that whole JSON object was around 300 bytes. It easily fit inside the 4KB limit. But on our personal accounts, which had logged in dozens of times during testing, that session array had 10 or 15 items. The raw JSON alone grew to about 2.6KB.Second, you can't put raw JSON characters like quotes, colons, and curly braces directly into a cookie header. So before setting the cookie, the backend ran the string through encodeURIComponent.Percent-encoding absolutely bloats JSON.Every quote turns into %22. Every bracket turns into %7B or %7D. Every colon turns into %3A. Every comma turns into %2C.In practice, percent-encoding regular JSON inflates the byte size by about 2.4 times.Our 2.6KB JSON string ballooned into over 6,100 bytes of encoded text. Once you add the cookie name and the security flags, the header clocked in at 6,320 bytes. Chrome took one look, saw it was over 4,096 bytes, and silently threw it in the trash.Then the browser followed the 302 redirect to the dashboard. The dashboard found no cookie, figured nobody was logged in, and redirected back to the login page.Email and password login never had this problem because the user data returned in the HTTP response body has no 4KB limit. The frontend read the body, saved it to localStorage, and navigated cleanly.To fix it properly, we changed three things.First, we stopped storing database models in cookies. A cookie should only be a pointer, not a database row.We trimmed the cookie payload down to just the essentials: an ID string, a name, an email, and the role. We stripped out all the session history and audit arrays. That immediately dropped our cookie size from 6,320 bytes down to around 210 bytes.Second, we stopped relying only on cookies for the OAuth handoff. Since browser cookie rules and privacy blockers keep getting stricter, we updated our 302 redirect to also pass a one-time handoff token in the URL query string, like /dashboard?auth_success=true&uid=123.Third, we updated our frontend auth hook to check the URL query parameters on mount. If it sees auth_success=true, it immediately fires a background fetch request to our user profile endpoint to pull the full user object over a normal HTTP body.As soon as that request finishes and localStorage is updated, the frontend calls window.history.replaceState to scrub the query parameters out of the URL bar so the user never sees them.If the cookie works, the dashboard loads instantly. If a browser policy or an aggressive privacy extension drops the cookie, the URL fallback catches it and logs the user in without a hitch.The biggest lesson for us was just how quiet browser networking failures can be.If your backend throws a 500 or your React code throws an exception, you get an immediate alert or a red error in your console.But when you violate an old HTTP cookie spec, the browser will quietly drop your data on the floor without telling anyone, leaving you to wonder why your perfectly valid redirect chain just vanished into thin air.

Original Source

Read the full article at Hackernoon →

KhanList aggregates and links to publicly available news content. We do not host full articles from third-party sources. Always verify important information with original sources.