2017-07-25 92 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。感謝所有的幫助。