Fix HTTP431 Request header fields too large

We’re developing an aspnet core website with webapi backend all on a cloud platform. The auth part is implemented with openidconnect and cookies. Every tab is a new application to reduce release and test times. For the website / applications we have a razor class library that contains the main layout. See all posts in this series cloudnative

Today we received feedback that some users experience a HTTP431 exception when browsing the website. This was right after we added the access_token so it had to be that. The message is “request header fields too large” – would this be the feared token bloat where some users would have endless claims making the token too large?

Turns out we’re not alone and the solution for this was already on GitHub: https://github.com/dotnet/aspnetcore/issues/30016. Our solution was to remove SaveTokens = true and add the access_token on the OnTokenResponseReceived event (we’re using codeflow) Solution in code below.

.AddOpenIdConnect(opt =>
  // o.SaveTokens = true; // results in HTTP431 for some users
  opt.Events = new OpenIdConnectEvents() {
    OnTokenResponseReceived = c => {
      c.Properties.StoreTokens(new[] { 
        // store only the access_token
        new AuthenticationToken {
          Name = "access_token",
          Value = c.TokenEndpointResponse.AccessToken
        }
      });
      return Task.CompletedTask;
    }
  };

In the developer tools (F12) on the application tab you can see the cookie for the website. With SaveTokens = true it would be 7 or more chunks. After the change the cookie was only 2 chunks. Problem solved.

Unknown's avatar

About erictummers

Working in a DevOps team is the best thing that happened to me. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged . Bookmark the permalink.

1 Response to Fix HTTP431 Request header fields too large

  1. Pingback: Call upstream api with token | .NET Development by Eric

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.