AspNet Core Identity - cookie not getting set in p

2019-02-22 01:04发布

问题:

I have a .NET Core 2 web app and I want to use ASP.NET Identity to authenticate my users. On .NET Core 1.x, my code was working fine.

I migrated to .NET Core 2, and authentication works when running locally in Visual Studio. But when I deploy to a live environment, authentication stops working: the authentication cookie isn't being set in production.

My Startup.cs code looks like this:

public void ConfigureServices(IServiceCollection services)
{
   services.AddIdentity<AppUser, RavenDB.IdentityRole>()
         .AddDefaultTokenProviders(); 

   ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   ...

   app.UseAuthentication();
}

To sign in, my code looks like this:

public async Task<ActionResult> SignIn(...)
{
   var user = ...; // Load the User from the database.
   await this.signInManager.SignInAsync(user, isPersistent: true);

   ...
}

This code works locally: the ASP.NET Identity auth cookie is set. However, when I deploy this to production enviro in Azure, the cookie never gets set.

What am I missing?

回答1:

I solved the problem. It boiled down to HTTPS: it appears that signInManager.SignInAsync(...) sets a cookie that is HTTPS-only. I was publishing to a non-HTTPS site initially for testing.

Once I published to an HTTPS site, the cookie started working again.

The reason it was working locally was that I was running in HTTPS locally.



回答2:

Had same problem with Chrome 60+. Cookie did not want to set on HTTP site or even HTTPS and Cordova.
options.Cookie.SameSite = SameSiteMode.None;
https://github.com/aspnet/Docs/blob/master/aspnetcore/security/authentication/cookie.md
Changing from default value (Lax) to None fixed it for me.