Search code examples
asp.net-core-mvcasp.net-core-6.0cookie-authentication

ASP.NET Core MVC - cookie authentication: can a malicious user edit their cookie to give themselves more permissions?


TL;DR Can a malicious user modify their cookie so they have claims they should not, or is the cookie string encrypted or protected in some way?

I've implemented cookie authentication in my ASP.NET Core 6.0 MVC application.

Program.cs

builder.Services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            options.SlidingExpiration = true;
            options.AccessDeniedPath = "/Forbidden/";
            options.Cookie.Name = "IANSW_Session";
            options.Cookie.HttpOnly = true;
        });

In my login controller the SignInAsync method is called like this:

var authProperties = new AuthenticationProperties();
var claims = await _claimsService.GetClaimsForUsername(userResult.Username);
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

Now, one of these claims will be a CanEditPosts claim. The 'EditPost' action looks something like this:

[Authorize("CanEditPosts")]
public async Task<IActionResult> EditPost(int postId)
{
    if (!User.Identity.IsAuthenticated) return Json("Error");

    var userPosts = _userPostService.GetAllUserPostsIDs(User.Identity.Name);

    if (userPosts.Contains(postId))
    {
        // User is trying to edit one of their own posts
    }

    // etc...
}

My question: is it possible for a user to edit their own cookie to give themselves the CanEditPosts claim, or perhaps change their Name in the cookie so the code thinks someone else's posts belongs to them?

I can see in my browsers dev tools the cookie looks like this, but I have no idea if this is encrypted or protected in some other way.

enter image description here


Solution

  • From microsoft documentation:

    SignInAsync creates an encrypted cookie and adds it to the current response.

    ASP.NET Core's Data Protection system is used for encryption.