Search code examples
asp.net-mvccookiesasp.net-identityasp.net-core-mvcclaims-based-identity

Retrieve Userid from a claims in a cookie in Core MVC


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


Solution

  • 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();
    }