Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor WebAssembly (WASM) App cookie consent value

$
0
0

ASP.NET Core offers EU General Data Protection Regulation (GDPR) support out of the box with a cookie consent feature:

https://learn.microsoft.com/en-us/aspnet/core/security/gdpr?view=aspnetcore-7.0

Program.cs

builder.Services.Configure<CookiePolicyOptions>(options =>{    // This lambda determines whether user consent for non-essential     // cookies is needed for a given request.    options.CheckConsentNeeded = context => true;    options.MinimumSameSitePolicy = SameSiteMode.None;});builder.Services.AddHttpContextAccessor();app.UseCookiePolicy();

A Blazor Server App can use nearly the same code and make it work:

ConsentCookie.razor

@using Microsoft.AspNetCore.Http.Features@using Microsoft.AspNetCore.Http@inject IHttpContextAccessor Http@inject IJSRuntime JSRuntime@if (showBanner){<div id="cookieConsent" class="alert alert-info alert-dismissible fade show" role="alert">        Consent to set cookies.<button type="button" class="accept-policy close" data-dismiss="alert" aria-label="Close" data-cookie-string="@cookieString" @onclick="AcceptMessage">            Accept Cookie</button></div>}@code {    ITrackingConsentFeature consentFeature;    bool showBanner;    string cookieString;    protected override void OnInitialized()    {        consentFeature = Http.HttpContext.Features.Get<ITrackingConsentFeature>();        showBanner = !consentFeature?.CanTrack ?? false;        cookieString = consentFeature?.CreateConsentCookie();    }    private void AcceptMessage()    {        // JsInterop call to store the consent cookies.        JSRuntime.InvokeVoidAsync("CookieFunction.acceptMessage", cookieString);    }}

_Host.cshtml

<script>    window.CookieFunction = {        acceptMessage: function (cookieString) {            document.cookie = cookieString;        }    };    </script>

MainLayout.razor

<div class="page"><div class="main"><ConsentCookie /><div class="content px-4">            @Body</div></div></div>

https://www.syncfusion.com/faq/blazor/tips-and-tricks/how-do-i-set-consent-cookies-in-blazor

However since Blazor WebAssembly (WASM) apps run client-side the HttpContext features wont work. How can I add cookie consent for Blazor WebAssembly (WASM) without using any third party library like Majorsoft.Blazor.Components.GdprConsent?

https://www.nuget.org/packages/Majorsoft.Blazor.Components.GdprConsent/https://github.com/dotnet/AspNetCore.Docs/issues/18055#issuecomment-881316391https://www.reddit.com/r/Blazor/comments/vfx8h4/blazor_wasm_gdpr_and_cookie_consent/

I don't want to use Blazored LocalStorage to access local storage either.

https://github.com/Blazored/LocalStorage


Viewing all articles
Browse latest Browse all 4839

Trending Articles