Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include credentials when making CORS requests from Blazor?

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.

like image 224
Amit Avatar asked Oct 16 '25 02:10

Amit


1 Answers

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) });
like image 171
Kanawanagasaki Avatar answered Oct 18 '25 18:10

Kanawanagasaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!