I’m using the blazor web application with auto interaction and individual accounts, I’m trying to make a request to the API but the cookies aren’t passed on in the request, how do I add them?
return await _httpClient.GetFromJsonAsync<List<UserDTO>>("api/users");
I need suggestions, I’ve been trying to solve this problem for some time, but without success.
7
There is no built-in way for the demand. You will need to get the authentication cookie on your own. After login, then asp.net core identity cookie will be generated to the domain with the cookie name .AspNetCore.Identity.Application
Then you need to get the cookie before httpclient request. WASM will experience 2 rendermodes: prerender and interactive. (https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-context?view=aspnetcore-8.0#ihttpcontextaccessorhttpcontext-in-razor-components-blazor)
When prerender : HttpContext is available. Js Interop not available. You could get cookie by httpContext.request.cookie.
When interactive : HttpContext is not available. Js Interop is available. You could get cookie by javascript “document.cookie”.
So you could do following :
Install Microsoft.AspNetCore.Http 2.2.2
at client project, then call backend in an WASM page like
@page "/counter"
@using Microsoft.AspNetCore.Http
@rendermode InteractiveWebAssembly
@inject IJSRuntime _js
@data
<script>
function ReadCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>
@code {
string data = "";
[CascadingParameter]
HttpContext? httpContext{ get; set; }
protected override async Task OnInitializedAsync()
{
string authcookie;
if (httpContext != null)
{
//when prerender get cookie from httpContext
authcookie = httpContext.Request.Cookies[".AspNetCore.Identity.Application"];
}
else
{
//when interactive get cookie by js interop
authcookie = await _js.InvokeAsync<string>("ReadCookie", ".AspNetCore.Identity.Application");
}
if (authcookie != null)
{
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7264/test"); //the [Authorize] webapi endpoint
// Add a cookie to the request headers
request.Headers.Add("Cookie", $".AspNetCore.Identity.Application={authcookie}");
// Send the request
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
data = await response.Content.ReadAsStringAsync();
}
}
else
{
data = "no authentication cookie";
}
}
}
Need to set cookie httponly to false in server project program.cs.
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = false;
});
12