locked
after logging into asp.net core webiste with identity user won't stay logged in RRS feed

  • Question

  • User-536896575 posted

    I'm very new to learning asp.net core and using user identity within this web application, but after couple weeks of messing around i somehow lost the ability to stay logged in within the website i've created and have been testing with.  it will let me log in, but as soon as i navigate to the next page i'm immediately logged out.  Is there a setting within the startup.cs or somewhere that i can change or set that keeps me logged in?  if someone could point me in the right direction any help is appreciated!

    Saturday, February 8, 2020 12:17 AM

All replies

  • User665608656 posted

    Hi mike11d11,

    Based on your question, in order to get the ASP.NET Core pipeline to recognise that a user is signed in, a call to UseAuthentication is required in the Configure method of your Startup class.

    I suggest you confirm that your startup.cs file adds the following code:

    app.UseAuthentication ();​
    app.UseMvc ();

    Or you can try clearing your browser's cookies and cache and retesting.

    More details, you can refer to this link :  Asp.net core Identity successful login redirecting back to login page


    Best Regards,
    YongQing.

    Monday, February 10, 2020 5:42 AM
  • User-536896575 posted

    Yes i already have this code, i couldnt use the app.UseMvc() for it says its not supported while using EndPoint routing.  this is the code in my Configure..

    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    else
    {
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSession();
    app.UseRouting();

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

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

    });

    CreateUserRoles(services).Wait();

    Monday, February 10, 2020 3:01 PM
  • User665608656 posted

    Hi mike11d11,

    Do you set the expiration date of cookies in the code?

    I suggest you can use F12 tool to check whether the asp.net identity cookie is normal.

    Best Regards,

    YongQing.

    Tuesday, February 11, 2020 5:55 AM
  • User-536896575 posted

    I tried adding this code but it doesnt seem to be creating the cookie?

    services.ConfigureApplicationCookie(options =>
    {
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.Cookie.Name = "identityCookie";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
    options.LoginPath = "/Identity/Account/Login";
    // ReturnUrlParameter requires
    //using Microsoft.AspNetCore.Authentication.Cookies;
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
    });

    Tuesday, February 11, 2020 6:47 PM
  • User302204515 posted

    Hi,

    I think you can try to use fiddler to capture a http trace and see if asp.net core identity correctly set your cookie right after you login

    Thursday, February 13, 2020 2:18 AM
  • User-536896575 posted

    When i run fiddler and check the cookies tab it says "This response did not set any cookies"?

    Sunday, February 16, 2020 7:39 PM
  • User-536896575 posted

    I for sure throught this might have been teh solution being GDPR and essential cookies but no.  Not sure what else could be breaking my app and not keeping the user logged in?

    https://stackoverflow.com/questions/52456388/net-core-cookie-will-not-be-set

    Wednesday, February 19, 2020 8:14 PM
  • User302204515 posted

    Let's isolate the issue from auth and cookie setting, can you try adding a new page that allows anonymity access and set a cookie in that page, than check in fiddler if asp.net core correct responding with a set cookie header.

    Friday, February 21, 2020 8:21 AM
  • User-536896575 posted

    Looks like it it is setting the cookie in fiddler from what i can tell, looking at the headers tab under the cache section it show this below which doesnt look correct as far as the expires section and the cookie i was naming in the settings is TestAuthCookie..

    Cache
    cache-control: no-cache
    Date: Sun, 23 Feb 2020 22:20:05 GMT
    Expires: Thu, 01 Jan 1970 00:00:00 GMT
    Pragma: no-cache

    Cookies / Login
    Set-Cookie: .AspNetCore.Identity.Application...
    Set-Cookie: .AspnetCore.Mvc.CookieTempDataProvider...
    Set-Cookie: TestAuthCookie....

    Sunday, February 23, 2020 10:28 PM
  • User-536896575 posted

    Here is my code in my startup configureService 

    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
    services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().AddUserManager<UserManager<ApplicationUser>>().AddDefaultTokenProviders();
     services.AddAutoMapper(Assembly.GetExecutingAssembly());

                services.AddScoped<INoteRepository, NoteRepository>();
                services.AddScoped<IPatientRepository, PatientRepository>();
                services.AddScoped<ILOCRepository, LOCRepository>();
                services.AddScoped<IAssessmentRepository, AssessmentRepository>();

                services.AddHttpContextAccessor();
                services.AddSession();
                services.AddControllersWithViews();

                services.AddRazorPages();           
                services.AddMvc();

    and here is the code for the Configure in startup

      if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }

                app.UseHttpsRedirection();
                app.UseStaticFiles();
                //app.UseSession();
                app.UseRouting();   
                app.UseCookiePolicy();
              

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

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

                });

                CreateUserRoles(services).Wait();

    I put this code below on my home index page where i get routed once logged in.  When i'm redirected there it determines i'm logged in, but if i immediately refresh the page then i'm not authenticated??

    @if (User.Identity.IsAuthenticated)
    {
        <div>User is authenticated!</div>   
    }
    else
    {
        <div>User is not authenticated!</div>   
    }

    Monday, February 24, 2020 4:20 AM
  • User302204515 posted

    It appears that in your configservice you didn't config your cookie setting.

    Modify your AddIdentity extension method as below

    services.AddIdentity<ApplicationUser,IdentityRole>(config=>{

    config.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(1); config.Cookies.ApplicationCookie.LoginPath = "/Account/LogIn"; config.Cookies.ApplicationCookie.LogoutPath = "/Account/LogOut";

    })

    Monday, February 24, 2020 7:35 AM
  • User-536896575 posted

    I'm using asp.net core 3.1 which might be why when i add those config options for the cookie it says

    "Severity Code Description Project File Line Suppression State
    Error CS1061 'IdentityOptions' does not contain a definition for 'Cookies' and no accessible extension method 'Cookies' accepting a first argument of type 'IdentityOptions' could be found (are you missing a using directive or an assembly reference?)"

    Another way of doing this in 3.1?

    Tuesday, February 25, 2020 2:12 AM
  • User302204515 posted

    for 3.1, you can check this document

    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-configuration?view=aspnetcore-3.1#cookie-settings

    Tuesday, February 25, 2020 2:15 AM
  • User-536896575 posted

    Still same with these settings

    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>().
    AddUserManager<UserManager<ApplicationUser>>().AddDefaultTokenProviders();

    services.ConfigureApplicationCookie(options =>
    {
    options.AccessDeniedPath = "/Identity/Account/AccessDenied";
    options.Cookie.Name = "YourAppCookieName";
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(10);
    options.LoginPath = "/Identity/Account/Login";
    //ReturnUrlParameter requires
    //using Microsoft.AspNetCore.Authentication.Cookies;
    options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
    options.SlidingExpiration = true;
    });

    services.AddAutoMapper(Assembly.GetExecutingAssembly());

    services.AddScoped<INoteRepository, NoteRepository>();
    services.AddScoped<IPatientRepository, PatientRepository>();
    services.AddScoped<ILOCRepository, LOCRepository>();
    services.AddScoped<IAssessmentRepository, AssessmentRepository>();

    services.AddHttpContextAccessor();
    services.AddSession();
    services.AddControllersWithViews();

    services.AddRazorPages();
    services.AddMvc();

    Tuesday, February 25, 2020 2:49 AM
  • User-536896575 posted

    Also when i clear my cookies in chrome it recreates the antiforgery cookie, then my "YourAppCookieName" cookie but immediately disappears within a split second of populating, almost like it expires immediately?

    Tuesday, February 25, 2020 3:01 AM
  • User2125792688 posted

    Did you try it in different browsers? Is there any chance your browser does not accept cookies? I had the same problem and tried everything for an hour. Then i realized my chrome browser cookie settings have changed to "block all cookies". 

    Saturday, January 2, 2021 2:10 PM