How to manage ASP .NET Cookies. How is cookie security provided?

How to manage ASP .NET Cookies. How is cookie security provided?


First of all, I recommend you to research What CookieOptions parameters do and What is Microsoft.AspNetCore.DataProtection and why we should use it.

Check and publish the configurations we will have made below. Since the data will be encrypted, you may encounter temporary problems as the encrypted data will be affected in your next changes.

Let's start coding. We add that we will use DataProtection to our services in ConfigureServices in Startup.cs. Here we create the DataProtection Key to our system and introduce it to our system.

services.AddDataProtection()
    .SetDefaultKeyLifetime(TimeSpan.FromDays(365 * 2))
    .PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + "/AppData"))
    .SetApplicationName("YourAppName");

Our encryption library and configurations are ready. Now let's create our class where we will manage cookies. (If you can't find the SameSiteMode.Unspecified property, update your SDK or use an alternative SameSiteMode.Lax.)

public static class CookieManager
{
    private static CookieOptions GetCookieOptions()
    {
        return new()
        {
            HttpOnly = true,
            Expires = DateTime.Now.AddDays(60),
            Secure = true,
            SameSite = SameSiteMode.Unspecified,
            IsEssential = true
        };
    }

    public static bool HasCookie(HttpContext context, string key)
    {
        return context.Request.Cookies.ContainsKey(key);
    }

    public static void SetCookieObjectAsJson(HttpContext context, string key, object value)
    {
        if (context.Request.Cookies[key] != "null" && context.Request.Cookies[key] != null)
            context.Response.Cookies.Delete(key);
        var protector = context.RequestServices.GetDataProtector("YourProtectorKey");
        var data = protector.Protect(JsonConvert.SerializeObject(value));
        context.Response.Cookies.Append(key, data, GetCookieOptions());
    }

    public static T GetCookieObjectFromJson<T>(HttpContext context, string key)
    {
        var value = context.Request.Cookies[key];
        if (value == null)
            return default;
        var protector = context.RequestServices.GetDataProtector("YourProtectorKey");
        var data = protector.Unprotect(value);
        try
        {
            return JsonConvert.DeserializeObject<T>(data);
        }
        catch (Exception ex)
        {
            context.Response.Cookies.Delete(key);
            Console.WriteLine(ex);
            return default;
        }
    }

    public static void DeleteCookie(HttpContext context, string key)
    {
        context.Response.Cookies.Delete(key);
    }
}

Using this class, you can now securely manage your cookies as you wish. I will put two sample codes for adding and fetching cookies and say goodbye to you. When you want to use this class, it will be enough to give HttpContext.

var model = new User();
model.Id = 1;
model.Name = "Mehmet";
model.Surname = "Erdoğdu";
CookieManager.SetCookieObjectAsJson(HttpContext, "User" + model.Id, model);
CookieManager.DeleteCookie(HttpContext, "User" + model.Id);

There is no system that cannot be broken. You can just make it harder to break! Continue to research and develop new techniques...

An error has occurred. This application may no longer respond until reloaded. Reload 🗙