Search code examples
asp.net-corecorsblazor

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.


Solution

  • In your Startup.Configure method you can set the WebAssemblyHttpMessageHandler.DefaultCredentials to the required value of the 'credentials' option on outbound HTTP requests like this:

    public void Configure(IComponentsApplicationBuilder app)
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
                {
    
                    WebAssemblyHttpMessageHandler.DefaultCredentials = FetchCredentialsOption.Include;
                }
    
                app.AddComponent<App>("app");
            }
    

    References: https://github.com/aspnet/AspNetCore/blob/c39fbb8f12002f61df6c093b0c11e6bd585ee202/src/Components/Blazor/Blazor/src/Http/WebAssemblyHttpMessageHandler.cs

    https://github.com/aspnet/AspNetCore/blob/5a70f5312fb57fc3788e5af56a99e7b43761e195/src/Components/Blazor/Blazor/src/Http/FetchCredentialsOption.cs

    https://github.com/aspnet/AspNetCore/blob/d18a033b1ee6d923a72d440718c5d496b57c2ffc/src/Components/test/testassets/BasicTestApp/Startup.cs

    Hope this helps...