Forum Discussion
Http requests from client to server project with cookie auth
Hi , my best guess is
Your `@rendermode InteractiveAuto` runs **twice**.
On the **server prerender**, the backend calls itself. Since it's not running in a browser at that moment, there are **no cookies** attached to that initial `HttpClient` request. Boom, `401 Unauthorized`.
Fix 1: Disable Prerendering
If you don't care about SEO or immediate static HTML, just disable prerendering so it only runs on the WebAssembly client where cookies work naturally.
Change the top of your `Auth.razor` to:
@rendermode @(new InteractiveAutoRenderMode(prerender: false))
Fix 2: Forward Cookies during Prerender (Best Practice)
If you *must* keep prerendering, you need to forward the cookie from the user's incoming browser request to the backend `HttpClient`.
1. Add this in the **Server's** `Program.cs`:
builder.Services.AddHttpContextAccessor();
2. Register your `LocalHttpClient` on the **Server** side to clone the cookie:
builder.Services.AddHttpClient<LocalHttpClient>(client =>
{
client.BaseAddress = new Uri("https://localhost:7131/");
})
.ConfigurePrimaryHttpMessageHandler(sp =>
{
var httpContext = sp.GetRequiredService<IHttpContextAccessor>().HttpContext;
var handler = new HttpClientHandler();
if (httpContext != null && httpContext.Request.Cookies.TryGetValue(".AspNetCore.Identity.Application", out var cookie))
{
handler.CookieContainer = new System.Net.CookieContainer();
handler.CookieContainer.Add(new Uri("https://localhost:7131/"), new System.Net.Cookie(".AspNetCore.Identity.Application", cookie));
}
return handler;
});
*(Keep your original WebAssembly client registration as is, since the browser handles the cookie there).*