首页 > 解决方案 > 调用 HttpContext.SignInAsync 后 User.Identity.IsAuthenticated 为 false

问题描述

我正在使用 asp.net 核心并编写自定义登录。

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, "SomeUserName")
    // ... other stuffs
};

var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties();

var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    claimsPrincipal,
    authProperties);

此时一切正常,并且在浏览器中设置了 auth-cookie,但是下次我刷新页面时,在任何 controller.action 方法中,User.Identity.IsAhthenticatedisfalseUser.Identity.Namenull。

这也是我的startup.cs

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.SameSite = SameSiteMode.None;
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });

// ...
app.UseAuthentication();

我怎样才能得到User.Identity.IsAhthenticated真实?

标签: authenticationasp.net-core

解决方案


推荐阅读