locked
How to delete cookie after the browser closed in asp.net core RRS feed

  • Question

  • User-259252065 posted

    I'm implementing an asp.net core 3.1 project. My problem is I want when the user close the browser, the cookie goes to get deleted . For implementing the project, I authenticate the user via ldap with the below expression in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {

    services.AddControllersWithViews();

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


    services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
    {
    // Cookie settings

    //set the cookie name here
    options.Cookie.Name = "UserLoginCookie"; // Name of cookie
    options.Cookie.HttpOnly = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

    options.LoginPath = "/Account/Login";
    options.AccessDeniedPath = "/Account/UserAccessDenied";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.SlidingExpiration = true;
    });

    services.AddSession();
    services.AddSingleton<MySharedDataViewComponent>();
    services.AddHttpContextAccessor();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
    {
    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.UseSession();

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

    });
    }

    I have also a file  that is called, deleteCookie.js and its content is like the following:

    function deleteCookie(name) {
    setCookie(name, "", -1);
    }
    function setCookie(name, value, days) {
    if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
    }
    $(window).unload(function () {
    deleteCookie('UserLoginCookie');
    });

    function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
    c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
    return c.substring(name.length, c.length);
    }
    }
    return "";
    }

    And in my index view, I've written following code to use the deleteCookie.js and use the deleteCookie() function.

    <script language="JavaScript" type="text/javascript" src="~/js/deleteCookie.js"></script>

    @section Scripts{
    <script>
    $(window).unload(deleteCookie('UserLoginCookie'));
    console.log("coockie:" + getCookie('UserLoginCookie'));
    </script>

    }

    But my code doesn't work. I appreciae if anyone helps me to solve the issue.

    Saturday, August 1, 2020 8:35 AM

Answers

  • User475983607 posted

    Sorry, set it to false for the cookie to behave like Session.  The docs explain this :(

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 1, 2020 6:24 PM

All replies

  • User475983607 posted

    Set IsPersistent = true, when the cookie is created.  The official documentation covers the basics.

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

    JavaScript cannot access an auth (HTTP) cookie,

    Saturday, August 1, 2020 10:31 AM
  • User-259252065 posted

    Thank you for your help. I added isPersisted=true in my code but there wasn't any change. I need when user closes the browser, after reopening it see the login page. But in my code even after closing the browser and open it again, the user is in the app.

    public class AccountController : Controller
    {
    private readonly LDap.IAuthenticationService _authenticationService;
    private readonly IHttpContextAccessor _httpContext;

    private readonly CSDDashboardContext _context;

    public AccountController(LDap.IAuthenticationService authenticationService, IHttpContextAccessor context, CSDDashboardContext _context)
    {
    _context = _context;
    _httpContext = context;

    _authenticationService = authenticationService;
    }
    public IActionResult Login()
    {
    return View();
    }

    [HttpPost]
    // [ChildActionOnly]
    public async Task<IActionResult> Login(LoginModel model)
    {
    LdapEntry result1 = null;
    var result = _authenticationService.ValidateUser("mm.fr", model.UserName, model.Password);

    if (result)
    {
    var user = new Users().GetUsers().Where(u => u.UserName == model.UserName).SingleOrDefault();

    result1 = _authenticationService.GetLdapUserDetail("mm.fr", model.UserName, model.Password);
    ViewBag.Username = result1.GetAttribute("CN").StringValue;

    Index(result1.GetAttribute("CN").StringValue);

    var claims = new List<Claim>
    {

    new Claim("UserName", user.UserName),
    new Claim(ClaimTypes.Name, user.Name),
    new Claim(ClaimTypes.Email, user.EmailId),
    new Claim(ClaimTypes.Role, user.Role)

    };

    var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);


    var authProperties = new AuthenticationProperties
    {


    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),

    IsPersistent = true

    };
    await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);

    }
    else
    {
    this.TempData["ErrorMessage"] = "you entered wrong username or password";
    }
    return RedirectToAction(nameof(HomeController.Index), "Home");
    }

    public IActionResult Index(string str)
    {

    return View();
    }

    public ActionResult UserAccessDenied()
    {
    return View();
    }

    public async Task<IActionResult> Logout()
    {
    await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    return RedirectToAction(nameof(AccountController.Login), "Account");
    }
    }

    Saturday, August 1, 2020 12:42 PM
  • User475983607 posted

    Sorry, set it to false for the cookie to behave like Session.  The docs explain this :(

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, August 1, 2020 6:24 PM
  • User-259252065 posted

    Thank you for your reply. I did and set IsPersistent = false in my code but the problem still exists.

    Tuesday, August 4, 2020 1:53 PM
  • User753101303 posted

    Hi,

    What if you clear cookies to make sure the previously persisted cookie is deleted? You could also use https://developers.google.com/web/tools/chrome-devtools/storage/cookies to see which settings are currently in use for this cookie.

    A session cookie is  not persisted to disk and so by design shouldn't be kept when the browser (not just the site tab) is closed.

    Tuesday, August 4, 2020 2:36 PM
  • User475983607 posted

    Thank you for your reply. I did and set IsPersistent = false in my code but the problem still exists.

    Make sure you delete the persisted cookie.  Log out and log in.  

    Tuesday, August 4, 2020 3:00 PM
  • User-259252065 posted

    Thank you for your reply. I did it but it still doesn't work.

    Wednesday, August 5, 2020 5:59 AM
  • User753101303 posted

    And what if looking at this cookie using the previous link? You have the same tools in most if not all browsers.

    Also could you confirm you are closing the browser (ie all windows including the very last) before launching the browser again to see if you are still logged?

    Wednesday, August 5, 2020 7:27 AM
  • User-259252065 posted

    Thank you for your reply. I'm sorry I didn't understand what do you mean by "And what if looking at this cookie using the previous link?". Yes I close all my open browsers and tabs and then run my project again and still I see I'm logged in. 

    Wednesday, August 5, 2020 9:15 AM
  • User475983607 posted

    Thank you for your reply. I'm sorry I didn't understand what do you mean by "And what if looking at this cookie using the previous link?". Yes I close all my open browsers and tabs and then run my project again and still I see I'm logged in. 

    Share code that reproduces this behavior.

    Wednesday, August 5, 2020 10:41 AM
  • User753101303 posted

    You are testing with which browser? In most if not all web browsers you have https://developer.mozilla.org/en-US/docs/Learn/Common_questions/What_are_browser_developer_tools which allows to look at tons of things.

    It would allow to look at this cookie and see for example if it shows the expected lifetime rather than trying to guess (for example by testing if you still have the same behavior if you try to log 20 minutes, 1 hour or 1 day later).

    If you cleared all cookies and authentication is not asked again could it be some other issue such as having some controllers not requiring any user authentication at all to be used???

    Edit: if unsure the first thing I suggest is to show User.Identity.IsAuthenticated on a view for which you have this problem to make sure if the problem is really that the user is still authenticated or if the problem could be that a non authenticated user can still see this page.

    Wednesday, August 5, 2020 12:38 PM
  • User-259252065 posted

    Thank you all very much for the replies. The problem solved as you mentioned to set Persisted=false. I think my visual studio was reading from cache and that was the reason for problem.

    Sunday, August 16, 2020 12:17 PM