12

I want to store a userId in a cookie, in ASP.NET Core MVC. Where can I access it?

Login:

var claims = new List<Claim> {
    new Claim(ClaimTypes.NameIdentifier, "testUserId")
};

var userIdentity = new ClaimsIdentity(claims, "webuser");
var userPrincipal = new ClaimsPrincipal(userIdentity);
HttpContext.Authentication.SignInAsync("Cookie", userPrincipal,
    new AuthenticationProperties
    {
        AllowRefresh = false
    });

Logout:

User.Identity.GetUserId(); // <-- 'GetUserId()' doesn't exists!?

ClaimsPrincipal user = User;
var userName = user.Identity.Name; // <-- Is null.

HttpContext.Authentication.SignOutAsync("Cookie");

It's possible in MVC 5 ------------------->

Login:

// Create User Cookie
var claims = new List<Claim>{
        new Claim(ClaimTypes.NameIdentifier, webUser.Sid)
    };

var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(
    new AuthenticationProperties
    {
        AllowRefresh = true // TODO 
    },
    new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie)
);

Get UserId:

public ActionResult TestUserId()
{
    IPrincipal iPrincipalUser = User;
    var userId = User.Identity.GetUserId(); // <-- Working
}

Update - Added screenshot of the Claims which are null -------

userId is also null.

enter image description here

radbyx
  • 9,352
  • 21
  • 84
  • 127

2 Answers2

20

You should be able to get it via the HttpContext:

var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;

In the example context is the HttpContext.

The Startup.cs (just the basics as in the template website):

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app)
{
    app.UseIdentity();
    app.UseMvc();
}
kloarubeek
  • 2,706
  • 20
  • 24
  • Will test later. But I'm pretty sure I tryed "User.Claims" which are "null". I don't know why though :) – radbyx Dec 21 '16 at 21:32
  • It's also null. I'm sure your line is correct, but I must need something else I guess. Like something in StartUp.cs I have not added yet. ASP.NET Core MVC is new to me, so I might not have added all nesessary dependencies, for Claims to work. – radbyx Dec 22 '16 at 08:29
  • See added Screenshot :) – radbyx Dec 22 '16 at 08:29
  • and logout is a controller action? Maybe the user is already logged out? Is the value available after you logged in? – kloarubeek Dec 22 '16 at 11:05
  • Yes it's another Action. I have to the logic in another Action, before I can poke into the cookie. At least that's the way it was in MVC 5 when I made it there, if I remembered correct. – radbyx Dec 22 '16 at 11:39
  • put a breakpoint in it, maybe the action is visited twice: the first time the user is still logged in, but the second time it's logged out and the cookie is cleared. – kloarubeek Dec 22 '16 at 15:54
  • It's not that. I have a breakpoint and just below in the logiutbaction i call SignOutAsync(). Could you add your StartUp.cs to your answer? – radbyx Dec 22 '16 at 15:58
  • I have claims but don't know how to store in cookie –  Dec 16 '18 at 05:49
9

Using FindFirst method from ClaimsPrincipal class:

var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;

Andriy Tolstoy
  • 5,690
  • 2
  • 31
  • 30