从 Core MVC 中的 cookie 中的声明中检索 Userid

Retrieve Userid from a claims in a cookie in Core MVC

我想将 userId 存储在 ASP.NET Core MVC 中的 cookie 中。我在哪里可以访问它?

登录:

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

注销:

User.Identity.GetUserId(); // <-- 'GetUserId()' doesn't exists!?

ClaimsPrincipal user = User;
var userName = user.Identity.Name; // <-- Is null.

HttpContext.Authentication.SignOutAsync("Cookie");

在 MVC 5 中是可能的 ------------------>

登录:

// 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)
);

获取用户ID:

public ActionResult TestUserId()
{
    IPrincipal iPrincipalUser = User;
    var userId = User.Identity.GetUserId(); // <-- Working
}

更新 - 添加了无效声明的屏幕截图 ------

userId 也是 null.

您应该可以通过 HttpContext 获取它:

var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;

示例中 context 是 HttpContext。

Startup.cs(只是模板网站中的基础知识):

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    services.AddMvc();
}

public void Configure(IApplicationBuilder app)
{
    app.UseIdentity();
    app.UseMvc();
}

使用 FindFirst method from ClaimsPrincipal class:

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