azureasp.net-corecookiesblazor

Communication Issue Between API and WebAssembly on Azure Due to Extra Cookies


I am trying to implement an API and a WebAssembly in .NET Core on Azure. However, after deployment, I noticed that the communication between both stopped working.

Upon investigation, I found that there are two additional cookies beyond the expected ones: ARRAffinity and .AspNetCore.Identity.Application. My application, however, should only be using the .AspNetCore.Identity.Application cookie. I am unsure where the other cookies are being generated from, but I believe they may originate from Azure itself.

I would like to know how I can resolve this issue and ensure that only the .AspNetCore.Identity.Application cookie is used, removing any interference from the other cookies.

Locally, on my machine, the API and the WebAssembly work correctly, with only the .AspNetCore.Identity.Application cookie.

I am using BLAZOR.

    program.cs in WebAssembly:
    
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");
    builder.RootComponents.Add<HeadOutlet>("head::after");
     
    builder.Services.AddRadzenComponents();
    
    builder.Services.AddScoped<CookieHandler>();
    builder.Services.AddAuthorizationCore();
    builder.Services.AddScoped<AuthenticationStateProvider, AuthAPI>();
    builder.Services.AddScoped<AuthAPI>(sp => (AuthAPI)sp.GetRequiredService<AuthenticationStateProvider>());
    builder.Services.AddCascadingAuthenticationState();
     
    builder.Services.AddScoped<Status>();
      
    builder.Services.AddHttpClient("API", client => {
        client.BaseAddress = new Uri(builder.Configuration["API:Url"]!);
        //  client.BaseAddress = new Uri("https://localhost:7089/");
        client.DefaultRequestHeaders.Add("Accept", "application/json");
    }).AddHttpMessageHandler<CookieHandler>();
    
    await builder.Build().RunAsync();

On the API side, everything seems to be normal. When I use PostMan or Swagger, everything works fine. The problem arises when I use Blazor. In the API Server:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddDbContext<HContext>((options) =>
{
    options
            .UseSqlServer(builder.Configuration["ConnectionStrings:HDB"])
            .UseLazyLoadingProxies();
});

void UseLazyLoadingProxies()
{
    throw new NotImplementedException();
}

builder.Services
    .AddIdentityApiEndpoints<IdentityUser>()
    .AddEntityFrameworkStores<Context>();

builder.Services.AddAuthentication();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options => options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

builder.Services.AddCors(
    options => options.AddPolicy(
        "wasm",
        policy => policy
            .AllowAnyMethod()
            .SetIsOriginAllowed(pol => true)
            .AllowAnyHeader()
            .AllowCredentials()));

builder.Services.ConfigureApplicationCookie(options => { 
    options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; options.Cookie.SameSite = SameSiteMode.None; options.Cookie.Name = ".AspNetCore.Identity.Application"; options.LoginPath = "/login"; options.LogoutPath = "/Identity/Logout"; options.AccessDeniedPath = "/"; });


var app = builder.Build();

app.UseHttpsRedirection();

app.UseCors("wasm");

app.UseStaticFiles();

app.UseCookiePolicy();

app.UseAuthorization();

app.MapCustomIdentityApi<IdentityUser>();

app.MapControllers();

app.UseSwagger();

app.UseSwaggerUI();

app.UseMiddleware<ReadMe.Metrics>();

app.Run();

I’m sharing more code here to help with troubleshooting. It works fine with localhost. This could be something in Azure that is not properly receiving requests from a different URL for my API. This is why I need help.


Solution

  • how I can resolve this issue and ensure that only the .AspNetCore.Identity.Application cookie is used, removing any interference from the other cookies.

    To remove ARRAffinity cookies, turn off Session Affinity in the General Settings section under Configuration in Azure Web App as shown below.

    enter image description here

    enter image description here

    I noticed that the communication between both stopped working.

    Add the Azure App service backend API URL to the frontend Program.cs like this:

    builder.Services.AddHttpClient<AuthAPI>(client =>
    {
        client.BaseAddress = new Uri("https://<BackendAzureWebAppName>.canadacentral-01.azurewebsites.net");
    });
    

    Enable Cors in the Backend app and allow Azure Frontend URL.

    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowWasm",
            policy => policy.WithOrigins("https://<FrontendAzureWebAppName>.canadacentral-01.azurewebsites.net") // Update with actual WASM URL
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
    });
    app.UseCors("AllowWasm");
    

    This will make it proper communication between two apps.

    Azure Output:

    enter image description here

    enter image description here

    enter image description here