ASP.NET Core身份验证Cookie仅收到一次 [英] ASP.NET Core authentication cookie only received once

查看:88
本文介绍了ASP.NET Core身份验证Cookie仅收到一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Core开发应用程序,并且正在使用自定义Cookie身份验证.我的CookieAuthenticationOptions是:

I am developing an application with ASP.NET Core and I am using a custom Cookie Authentication. My CookieAuthenticationOptions are:

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

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

The cookie is created just fine and I can see it in the browser settings throughout the whole time I am running the application. This is my 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");
    }
}

这是我登录用户的方式:

And this is how I sign in the user:

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.

I am running the application and more than one instances of the HomeController are created, since I have HttpGet methods that return a JsonResult that is needed for the view.

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

The first time the application tries to [Authorize] (for the Index() method), it finds the cookie and authenticates and authorizes fine. The second time it tries to [Authorize] (for an HttpGet method that returns a JsonResult) it doesn't find the cookie, even though it is there in my browser's settings. This is the log I get, to illustrate this:

...
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

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

Why does this happen? What can I do about it?

推荐答案

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

The issue had nothing to do with the backend. I am using React in the front-end and the problem was that fetch() was not passing the cookies to the back-end for the GETmethods. I just had to set { credentials: 'same-origin' } to fetch() in order to send the cookies with the request. Thanks for all the help.

这篇关于ASP.NET Core身份验证Cookie仅收到一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆