tocoolforscool
tocoolforscool

Reputation: 452

How to access cookie asp.net core

var claims = new[]
{
  new Claim("UserID", user.ID.ToString()),
  new Claim(ClaimTypes.Role, "pioneer")
};

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

await HttpContext.Authentication.SignInAsync("Cookies", principal);

This is the cookie that I'm creating and using to sign in as per instruction from this tutorial: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie

The cookie is being created, but I don't know how to access the cookie or the data inside of it to get the user.ID value.

Upvotes: 1

Views: 1924

Answers (1)

travis.js
travis.js

Reputation: 5281

Once you sign via HttpContext.Authentication.SignInAsync, you should be able to access the User property in your controllers (it is part of ControllerBase), or HttpContext.User.

This User is a ClaimsPrincipal object that is created from the cookie automatically.

Upvotes: 3

Related Questions