ASP.NET Core身份validationcookie只收到一次
我正在使用ASP.NET Core开发应用程序,我正在使用自定义Cookie身份validation。 我的CookieAuthenticationOptions
是:
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme, LoginPath = new PathString("/login"), AccessDeniedPath = new PathString("/unauthorized/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
cookie创建得很好,我可以在运行应用程序的整个过程中在浏览器设置中看到它。 这是我的HomeController
类:
public HomeController(IHostingEnvironment env, IAntiforgery antiforgery, IOptions appSettings, TerminalDbContext terminalContext, ILoggerFactory loggerFactory, IHttpContextAccessor _httpContextAccessor) { _env = env; _antiforgery = antiforgery; _appSettings = appSettings; _terminalContext = terminalContext; _logger = loggerFactory.CreateLogger(); _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 { 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
方法返回视图所需的JsonResult
。
应用程序第一次尝试[Authorize]
(对于Index()
方法)时,它会找到cookie并进行身份validation和授权。 第二次尝试[Authorize]
(对于返回JsonResult
的HttpGet
方法),它找不到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。 谢谢你的帮助。