Retrieve Userid from a claims in a cookie in Core MVC

16,717

Solution 1

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

Solution 2

Using FindFirst method from ClaimsPrincipal class:

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

Share:
16,717
radbyx
Author by

radbyx

Backend developer at al dente. Former WebDeveloper at CapaSystems. I like to code in C#, MVC, JavaScript, Jquery, winforms, MSSQL, MySql ect. :) email: radbyx AT gmail DOT com

Updated on June 14, 2022

Comments

  • radbyx
    radbyx almost 2 years

    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
    radbyx over 7 years
    Will test later. But I'm pretty sure I tryed "User.Claims" which are "null". I don't know why though :)
  • radbyx
    radbyx over 7 years
    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
    radbyx over 7 years
    See added Screenshot :)
  • kloarubeek
    kloarubeek over 7 years
    and logout is a controller action? Maybe the user is already logged out? Is the value available after you logged in?
  • radbyx
    radbyx over 7 years
    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.
  • kloarubeek
    kloarubeek over 7 years
    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.
  • radbyx
    radbyx over 7 years
    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?
  • Admin
    Admin over 5 years
    I have claims but don't know how to store in cookie