Judah Gabriel Himango
Judah Gabriel Himango

Reputation: 60021

AspNet Core Identity - cookie not getting set in production

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?

Upvotes: 12

Views: 9405

Answers (3)

israel
israel

Reputation: 181

I had similar issue. In the startup.cs file, I had to change

app.UseCookiePolicy(new CookiePolicyOptions
{
     Secure = CookieSecurePolicy.Always
});

to

 app.UseCookiePolicy(new CookiePolicyOptions
 {
     Secure = CookieSecurePolicy.SameAsRequest
 });

This allowed cookie authentication to work on both http and https.

Upvotes: 1

aMerkuri
aMerkuri

Reputation: 173

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.

Upvotes: 3

Judah Gabriel Himango
Judah Gabriel Himango

Reputation: 60021

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.

Upvotes: 20

Related Questions