On a blazor client application, what is the equivalent of jQuery ajax WithCredentials
or JavaScript credentials: 'include'
?
With Javascript I am able to say:
fetch('https://www.example.com/api/test', {
credentials: 'include'
});
which includes auth cookie while making request and server responds with 200. I am trying to write same with Blazor using HttpClient
.
You can no longer set WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
in your Startup file to achieve js`s credentials: 'include'
To achieve this in newer versions of blazor, you need to create a class that derives from DelegatingHandler
, override SendAsync
method and set BrowserRequestCredentials
for request
to BrowserRequestCredentials.Include
public class CookieHandler : DelegatingHandler
{
public CookieHandler()
{
InnerHandler = new HttpClientHandler();
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
return base.SendAsync(request, cancellationToken);
}
}
After it pass your CookieHandler
to HttpClient
builder.Services.AddScoped(sp => new HttpClient(new CookieHandler()) { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With