2017-07-25 208 views
2

我正在开发一个ASP.NET Core应用程序,我正在使用自定义Cookie身份验证。我CookieAuthenticationOptions是:ASP.NET核心身份验证Cookie只收到一次

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](对于返回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 

为什么会发生这种情况?我能做些什么呢?

+1

您确定您在_both_个案中通过HTTPS发出请求吗? –

+0

我该如何检查? –

+0

我已经知道问题所在,谢谢你的帮助,我很快就会发表一个答案。 –

回答

1

该问题与后端无关。我在前端使用了React,问题是fetch()未将Cookie传递到GET方法的后端。我只需将{ credentials: 'same-origin' }设置为fetch()即可发送包含请求的Cookie。感谢所有的帮助。