Search code examples
c#cookiesasp.net-identity

How do I validate a user's cookie and extract their claims in identity framework?


I'm currently using Identity framework to create and store a cookie for the user. When the user attempts to login with the cookie, I'm unable to get the user claims from the cookie. Is there a way to decrypt the cookie when it is passed in or find it within the httpcontext?

I've tried searching the httpcontext, and I'm currently trying to find a way to decrypt the cookie that is passed in.

From startup.cs

 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.Cookie.Name = "MyCookie.Identity";

                    options.Cookie.Expiration = TimeSpan.FromDays(1);
                });

Where I create the cookie:


        private async void AddUserCookie(AuthRequest authRequest)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, authRequest.UserName),
                new Claim(ClaimTypes.Name, authRequest.UserName),
                new Claim(ClaimTypes.Email, "[email protected]")
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),
                IsPersistent = true,
                IssuedUtc = DateTimeOffset.UtcNow
            };

            await this._httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties).ConfigureAwait(false);

When I try to retrieve the cookie from the http context it says there's no claim's within the user's identity.


Solution

  • Answer is provided here: https://forums.asp.net/t/2157350.aspx?How+does+cookie+authentication+in+identity+framework+work+

    In short, I forgot to add app.UseAuthentication() in my startup.cs