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
.
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.
You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);
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.
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();
}
Using FindFirst method from ClaimsPrincipal class:
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With