2

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
});

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);

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.

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?

5
  • 1
    Are you sure you are making the request via HTTPS in both cases? Commented Jul 25, 2017 at 18:02
  • how do I check that? Commented Jul 26, 2017 at 7:21
  • I've figured out what the problem was, thanks for the help, I'll post an answer soon. Commented Jul 26, 2017 at 11:07
  • What was the problem? I notice whether I use cookies or basic authentication the User property on the HTTP context doesn't hydrate after about 60 seconds of inactivity. Commented Oct 19, 2017 at 16:54
  • @ScottWilson I posted an answer below. Commented Oct 20, 2017 at 9:04

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.