Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 432
radbyx Avatar asked Dec 20 '16 12:12

radbyx


People also ask

What is CookieAuthenticationDefaults AuthenticationScheme?

CookieAuthenticationDefaults. AuthenticationScheme provides “Cookies” for the scheme. In AddCookie extension method, set the LoginPath property of CookieAuthenticationOptions to “/account/login”. CookieAuthenticationOptions class is used to configure the authentication provider options. In Configure method of Startup.

How can we get logged in user details in ASP.NET Core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

How does cookie authentication work in NET Core?

There are 3 steps for using cookie authentication. First is to add authentication middleware with the AddAuthentication and AddCookie methods. Secondly, specify the app must use authentication & authorization. Finally apply the [Authorize] attribute on the controllers and actions that require the cookie authorization.


2 Answers

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();
}
like image 82
kloarubeek Avatar answered Nov 15 '22 22:11

kloarubeek


Using FindFirst method from ClaimsPrincipal class:

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

like image 25
Andriy Tolstoy Avatar answered Nov 15 '22 21:11

Andriy Tolstoy