【发布时间】:2017-12-31 14:15:56
【问题描述】:
我正在使用 ASP.NET Core 开发应用程序,并且正在使用自定义 Cookie 身份验证。我的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> 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 方法返回视图所需的JsonResult。
应用程序第一次尝试[Authorize](对于Index() 方法),它会找到cookie 并进行身份验证和授权。第二次尝试[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
为什么会这样?我该怎么办?
【问题讨论】:
-
您确定在 both 情况下通过 HTTPS 发出请求吗?
-
如何检查?
-
我已经找出问题所在,感谢您的帮助,我会尽快发布答案。
-
出了什么问题?我注意到我是否使用 cookie 或基本身份验证 HTTP 上下文上的 User 属性在大约 60 秒不活动后不会水合。
-
@ScottWilson 我在下面发布了一个答案。
标签: c# cookies asp.net-core asp.net-core-mvc session-cookies