ASP.NET Core 3.1 - Cookie Consent

This article will demonstrate the implementation of ASP.NET Core GDPR Consent features. I will assume you have downloaded the FREE ASP.NET Core 3.1 - FIDO Utilities Project or created a new ASP.NET Core 3.1 Razor Pages project. I won't use Identity or Individual User Accounts. See Tutorial: Get started with Razor Pages in ASP.NET Core.

FIDO Utilities Project and Article Series

The ASP.NET Core 3.1 - FIDO Utilities Project (FUP) is a collection of utilities I use in the ASP.NET Core 5.0 - Users Without Passwords Project (UWPP). I have upgraded the FUP with Bootstrap v5 and Bootstrap Native v4. FUP version 2.1 features SingleUser Authentication, Admin Page with Send Email Tests, ExceptionEmailerMiddleware, Bootstrap v5 Detection JavaScript, Copy and Paste Demo, Offcanvas Partial Demo, and Path QR Code Demo. The SMTP Settings Tester is updated and now located in the authorized Pages > Admin folder. The EmailSender and AES Cipher Demo are also updated. Registered users can download the source code for free on KenHaggerty. Com at Manage > Assets. The UWPP is published at Fido. KenHaggerty. Com.

Update 09/01/2021

I have upgraded the FUP with Bootstrap v5 and Bootstrap Native v4. I updated some of the article's images.

The Challenge demo implements the CookieTempDataProvider to persist the unique code called the challenge across requests. The CookieTempDataProvider encrypts and stores the challenge in a cookie. The early versions of the FIDO Utilities Project used the message modal to request the user's consent before the use of the temp data cookie.

Message Modal Cookie Consent.

When the user agreed, the Challenge demo page's DOMContentLoaded method would set the cookie. I developed a getChallengeConsent function in site.js to detect the consent cookie.

Challenge.cshtml > DOMContentLoaded
document.addEventListener('DOMContentLoaded', function () {
    if (getCookie('FidoUtilities.Challenge.CookieConsent') === '')
        setSessionCookie('FidoUtilities.Challenge.CookieConsent', true);
});
site.js > getChallengeConsent
function getChallengeConsent() {
    if (getCookie('FidoUtilities.Challenge.CookieConsent') === '') {
        showMessageModal('You are about to enter a page which uses cookies. By clicking the Countinue button, '
            + 'you agree with use of cookies otherwise click Cancel.', 'alert-warning', true, 'Cancel', '', true,
            '/Demos/Challenge', '_self', 'Countinue', 'btn-warning', false);
    }
    else
        window.location.href = '/Demos/Challenge';
}

When I decided to implement the ASP.NET Core GDPR Consent features as part of the FIDO Utilities Project, I encountered a new issue with the CookieTempDataProvider.

Temp Data Not Found.

If I accept the cookie policy from the _CookieConsentPartial. cshtml, the TempData cookie functions.

Challenge Verified.

Research found: Why isn't my session state working in ASP.NET Core? Session state, GDPR, and non-essential cookies, which lead to implementing the TempData cookie as essential.

Startup.cs > ConfigureServices
services.AddRazorPages()
    .AddCookieTempDataProvider(options =>
    {
        options.Cookie.IsEssential = true;
    });

This allowed the TempData to function without accepting the cookie policy.

Challenge Verified Is Essential.

This defeats the purpose of granting consent. To inform the user before navigating to the Challenge demo page, I needed to pass the CanTrack consent flag to JavaScript.

_Layout. cshtml before site.js loads
@@{
    var consentFeature = Context.Features.Get<ITrackingConsentFeature>();
    var mustAcceptCookies = !consentFeature?.CanTrack ?? false;
    if (mustAcceptCookies)
    {
        <script>
            var mustAcceptCookies = true;
        </script>
    }
}
site.js
function getChallengeConsent() {
    if (typeof mustAcceptCookies !== 'undefined' && mustAcceptCookies) {
        if (getCookie('.AspNet.Consent') === '')
            showMessageModal('You are about to enter a page which uses cookies. You must Accept the cookie policy.',
                'alert-warning', true, 'Cancel');
        else
            window.location.href = '/Demos/Challenge';
    }    
    else
        window.location.href = '/Demos/Challenge';
}
Must Accept Cookie Policy.
Must Accept Cookie Policy Mobile.

I noticed the cookie banner text appearing in search results. I moved the _CookieConsentPartial below the RenderBody div in _Layout. cshtml and added style to site.css.

Cookie Banner With Style.
Cookie Banner With Style Mobile.
Ken Haggerty
Created 05/10/20
Updated 09/02/21 01:53 GMT

Log In or Reset Quota to read more.

Successfully completed. Thank you for contributing.
Processing...
Something went wrong. Please try again.
Contribute to enjoy content without advertisments.
You can contribute without registering.

Comments(0)

Loading...
Loading...

Not accepting new comments.

Submit your comment. Comments are moderated.

User Image.
DisplayedName - Member Since ?