0

I need my application set a cookie so that the user must not login every time. I have decided for a 365 days cookie. The cookie seems to work only in localhost and not when i publish the application online. I have checked with Chrome and the cookie is set in both cases correctly. The name of the cookie is ".AspNetCore.Identity.Application" and it is set to expire in one year, both in localhost and on the server online. The cookie remains there even when the Session is over or the application shuts down, but in localhost I remain logged-in while online not.

Here is my Startup code:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddDbContext<ForumDbContext>(options =>
            options.UseSqlServer(Configuration["ConnectionString"]));

        services.AddIdentity<User, IdentityRole>(opts => {
            opts.Password.RequireDigit = false;
            opts.Password.RequiredLength = 7;
            opts.Password.RequireLowercase = false;
            opts.Password.RequireUppercase = false;
            opts.Password.RequireNonAlphanumeric = false;
            opts.SignIn.RequireConfirmedEmail = true;
        }).AddDefaultTokenProviders().AddEntityFrameworkStores<ForumDbContext>();

        services.ConfigureApplicationCookie(opts =>
        {
            opts.ExpireTimeSpan = TimeSpan.FromDays(365);
            
        }) ;

        services.AddAuthentication().AddCookie(options => {
             options.LoginPath = "/account/login"; 
             options.ExpireTimeSpan = TimeSpan.FromDays(365);                
        }) ;
        services.AddSession(opt => opt.IdleTimeout = TimeSpan.FromMinutes(100));

        services.AddSingleton<PathProvider>();
        services.AddSingleton<BlackList>();
        services.AddSingleton<HttpContextAccessor>();  //for the ISession
        services.AddScoped<UserSession>(sp => UserSession.CreateInstanceByService(sp));
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();

        var ci = new CultureInfo("it-IT");
        ci.NumberFormat.NumberDecimalSeparator = ",";
        ci.NumberFormat.CurrencyDecimalSeparator = ",";
        ci.NumberFormat.CurrencySymbol = "€";
        // Configure the Localization middleware
        app.UseRequestLocalization(new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(ci),
            SupportedCultures = new List<CultureInfo>
            {
                ci
            },
            SupportedUICultures = new List<CultureInfo>
            {
                ci
            }
        });

        app.UseSession();


        app.UseRouting();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });

        //Seeding the database
        using (IServiceScope serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {

            var dbContext = serviceScope.ServiceProvider.GetService<ForumDbContext>();
            var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
            var userManager = serviceScope.ServiceProvider.GetService<UserManager<User>>();

           DbSeeder.Seed(Configuration, dbContext, roleManager, userManager);

        }

    }
}

I have also checked that I pass IsPersistent = true in

await signinManager.PasswordSignInAsync(user, loginModel.Password, true, false)
user1238784
  • 2,250
  • 3
  • 22
  • 41
  • 1
    It doesn't look like you have configured data protection key storage, you often need to configure proper persisten storage for them in production so that existing cookies are not invalidated on new deployment and are accepted by all servers of a farm (if running on a server farm). Documentation: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.1 – juunas Nov 04 '20 at 15:13
  • I am running my application on a shared hosting. But your comment seems a bit unrelated to me. Why wouldn't the cookie be accepted, if it is stored in the browser cache – user1238784 Nov 04 '20 at 15:23
  • If data protection keys got re-generated (or are in-memory per instance), existing cookies would not be accepted anymore. – juunas Nov 04 '20 at 15:24
  • which modifications I should make to my code so that the cookie is accepted online? – user1238784 Nov 04 '20 at 15:38
  • You should check the options in the docs: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/web-farm?view=aspnetcore-3.1#data-protection. It depends on the kind of hosting you are using. – juunas Nov 04 '20 at 15:44
  • I am pretty sure I don't host on a web farm – user1238784 Nov 04 '20 at 16:19
  • 1
    I had same problem and this answer helped me: [Asp.Net core “remember me” persistent cookie not works after deploy](https://stackoverflow.com/a/47217955/2176905) – Farzaneh Talebi Nov 04 '20 at 17:44
  • @juunas I've been pulling my hair out off and on for weeks trying to figure out why authentication cookies wouldn't work after 30 minutes on my production server when they were set to expire much later. It's infuriating that they don't include anything in the starter template for this or have anything in the getting started documentation mentioning this. – Scott Wilson Feb 26 '21 at 17:46

0 Answers0