ASP.NET 核心身份验证 cookie 只收到一次

ASP.NET Core authentication cookie only received once

我正在开发一个带有 ASP.NET 核心的应用程序,并且我正在使用自定义 Cookie 身份验证。我的 CookieAuthenticationOptions 是:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
    LoginPath = new PathString("/login"),
    AccessDeniedPath = new PathString("/unauthorized/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

cookie 创建得很好,在我使用 运行 应用程序的整个过程中,我都可以在浏览器设置中看到它。这是我的 HomeController class:

public HomeController(IHostingEnvironment env,
    IAntiforgery antiforgery,
    IOptions<AppSettings> appSettings,
    TerminalDbContext terminalContext,
    ILoggerFactory loggerFactory,
    IHttpContextAccessor _httpContextAccessor)
{
    _env = env;
    _antiforgery = antiforgery;
    _appSettings = appSettings;
    _terminalContext = terminalContext;
    _logger = loggerFactory.CreateLogger<HomeController>();
    _httpContext = _httpContextAccessor.HttpContext;


    _logger.LogInformation("Cookie coming");
    var cookies = _httpContext.Request.Cookies[".AspNetCore.Cookies"];
    if (cookies != null)
    {
        _logger.LogInformation(cookies.Length.ToString());
        _logger.LogInformation(cookies.ToString());
    }
    else
    {
    _logger.LogInformation("THE COOKIE IS NULL");
    }
}

这就是我登录用户的方式:

var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, loginInfo.Username),
        new Claim("DbName", loginInfo.Terminal.SesamDbName),
    };

var userIdentity = new ClaimsIdentity(claims, "password");

ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await _httpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

我是 运行 应用程序并且创建了 HomeController 的多个实例,因为我有 HttpGet 方法 return a JsonResult这是视图所需的。

应用程序第一次尝试 [Authorize](对于 Index() 方法)时,它会找到 cookie 并进行身份验证和授权。它第二次尝试 [Authorize](对于 return 是 JsonResultHttpGet 方法)它没有找到 cookie,即使它存在于我的浏览器设置中.这是我得到的日志,以说明这一点:

...
info: Server.Controllers.HomeController[0]
      Cookie coming
info: Server.Controllers.HomeController[0]
      347
info: Server.Controllers.HomeController[0]
  CfDJ8GSLZENXaNpNrtmz2DAt9joqJ6CEHpCFbJdbNxbQYjjoQmd4naOI0L0krNMSQdVhqPRP9tJJMMIRayc5ILRQMcJQWNZ0T9Fjuk7Qxg65wPP7SR43UZxwy6vGQ7_qeSp44gYLLe4NGEalhXynZxmD-jywqL4VJZ5y4OwpsEKLx-VVT03xAlt54J_qQk_O4wjwLQiZBpAVTFKUWN4u7H8yd_rwMTIGBPu21t5n35To9bTQU5677xNxiEFap3ukuxO4p-OxVakXqShy2Xk_vYDAvv_XFV6jgNcy4ZiCRB8VUhXGcNr205h4X0-O7JHB8mYbc13aZLmrAwvG5DWTBd3_OCo
...
info: Server.Controllers.HomeController[0]
      Cookie coming
info: Server.Controllers.HomeController[0]
      THE COOKIE IS NULL

为什么会这样?我该怎么办?

该问题与后端无关。我在前端使用 React,问题是 fetch() 没有将 cookie 传递给 GET 方法的后端。我只需将 { credentials: 'same-origin' } 设置为 fetch() 即可随请求发送 cookie。感谢大家的帮助。