I am working on a blazor wasm app and want to authenticate at a WebApi (different base url). My problem is that blazor HttpClient does not respect cookies send by Server. Do you have any hints/idea how to solve this?
In the code below I am trying to attach cookie which I got from the server by the first request (successfull authentication)
Porgram.cs
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.Services.AddScoped<CustomDelegatingHandler>();
builder.Services.AddHttpClient("ServerAPI", client => client.BaseAddress = new Uri("https://test.myserver.com")).AddHttpMessageHandler<CustomDelegatingHandler>();
builder.Services.AddScoped<IHttpService, HttpService>();
builder.Services.AddScoped<ILoginService, LoginService>();
builder.Services.AddScoped<ISuncenterService, SuncenterService>();
await builder.Build().RunAsync();
}
CustomDelegatingHandler.cs looks like this
private readonly IJSRuntime JSRuntime;
public CustomDelegatingHandler(IJSRuntime jSRuntime) : base()
{
JSRuntime = jSRuntime;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
const string prm = "cookie";
string cookie = await JSRuntime.InvokeAsync<string>("blazorExtensions.GetCookie", new[] { prm
});
Console.WriteLine($"{prm}: {cookie}");
request.Headers.Add(prm, cookie);
return await base.SendAsync(request, cancellationToken);
}