Can anyone please provide
- A demonstration of how lax and strict (SameState) are implemented in Blazor application using Blazor web assembly and web app.
- How can we transfer and access cookie from one blazor site to another (hosted on different local host).
I tried to find quite a lot of tutorial and documentation on the same but could not find any.
In the WebAssembly App project add this code to add the cookie using the HttpClient
in program.cs file:
using BlazorWebAssemblyApp1;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
var httpClientHandler = new HttpClientHandler();
httpClientHandler.CookieContainer = new System.Net.CookieContainer();
var httpClient = new HttpClient(httpClientHandler)
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
};
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
Code to fetch cookie:
@page "/fetch-cookies"
@inject CookieService CookieService
<h3>Fetch Cookies</h3>
<button @onclick="FetchCookies">Fetch Cookies</button>
@if (!string.IsNullOrEmpty(LaxCookie))
{
<p>Lax Cookie: @LaxCookie</p>
}
@if (!string.IsNullOrEmpty(StrictCookie))
{
<p>Strict Cookie: @StrictCookie</p>
}
@code {
private string LaxCookie;
private string StrictCookie;
private async Task FetchCookies()
{
LaxCookie = await CookieService.GetCookieAsync("SameSiteCookieLax");
StrictCookie = await CookieService.GetCookieAsync("SameSiteCookieStrict");
}
}
Cookie.js :
window.blazorExtensions = {
GetCookie: function (name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
};
CookieService.cs:(To get the cookie from browser)
using Microsoft.JSInterop;
using System.Threading.Tasks;
public class CookieService
{
private readonly IJSRuntime _jsRuntime;
public CookieService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public async Task<string> GetCookieAsync(string name)
{
return await _jsRuntime.InvokeAsync<string>("blazorExtensions.GetCookie", name);
}
}
```
Add a JavaScript file (`wwwroot/cookies.js`) with the following content:
```javascript
window.blazorExtensions = {
GetCookie: function (name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length === 2) return parts.pop().split(";").shift();
}
};
Do not forgot to add js file in index file:
In the sever size program.cs file set cors policy to configure CORS to allow the Blazor WebAssembly app to access it and set a cookie with a specific SameSite policy
using BlazorServerApp.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowBlazorClient",
builder => builder
.WithOrigins("https://localhost:7112") // URL of your Blazor WebAssembly app
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("AllowBlazorClient");
app.Use(async (context, next) =>
{
context.Response.Cookies.Append("SameSiteCookieLax", "lax_value", new CookieOptions { SameSite = SameSiteMode.Lax });
context.Response.Cookies.Append("SameSiteCookieStrict", "strict_value", new CookieOptions { SameSite = SameSiteMode.Strict });
await next.Invoke();
});
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
app.Run();
2