radbyx
radbyx

Reputation: 9670

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

Upvotes: 13

Views: 26039

Answers (2)

Andriy Tolstoy
Andriy Tolstoy

Reputation: 6100

Using FindFirst method from ClaimsPrincipal class:

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

Upvotes: 10

kloarubeek
kloarubeek

Reputation: 2854

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

Upvotes: 20

Related Questions