Как удалить Cook ie при закрытии браузера - PullRequest
0 голосов
/ 11 июля 2020

Я реализую основной проект asp. net и аутентифицирую пользователя через ldap, используя Novell.Directory.Ldap.NETStandard. Теперь моя проблема: как я могу удалить cook ie после того, как пользователь закроет браузер. Я хочу, чтобы всякий раз, когда пользователь закрывает браузер и снова открывает систему, он сталкивается со страницей входа. вот что я пробовал при запуске для настройки cook ie:

 services.AddScoped<Ldap.IAuthenticationService, LdapAuthenticationService>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

                options.LoginPath = "/Account/Login";
                options.SlidingExpiration = true;

            });

А вот мой AccountController:

  public class AccountController : Controller {

        private readonly Ldap.IAuthenticationService _authenticationService;
        private readonly IHttpContextAccessor _httpContext;

        public AccountController(Ldap.IAuthenticationService authenticationService,IHttpContextAccessor 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.ValidateUser1("mm.fr", model.UserName, model.Password);
          
            if (result.Equals(true))
            {
                result1 = _authenticationService.GetLdapUserDetail("mm.fr", model.UserName, model.Password);
                ViewBag.Username = result1.GetAttribute("CN").StringValue;
 

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

                
                if (result != null)
                {
                    var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
                new Claim(ClaimTypes.Role, "Administrator"),
 
            };

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

                    var authProperties = new AuthenticationProperties
                    {

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

            }
            else
            {
                this.TempData["ErrorMessage"] = "Password is incorrect";
            }
            return RedirectToAction(nameof(MainDashboardController.Index), "MainDashboard");
        }
        public IActionResult Index(string str)
            {

            _httpContext.HttpContext.Session.SetString("mystr", str);

            return View();
        }
    }

Вот что я написал в Startup:

 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<CSDDashboardContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));


            //Notice this is NOT the same class... Assuming this is a valid DBContext.  You need to add this class as well.
            //services.AddDbContext<CSSDDashboardContext>(options =>
            //             options.UseSqlServer(Configuration.GetConnectionString("CSDDashboardContext")));
            //*---------------------------New Active Directory--------------------------------
            services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(15);

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

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

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

                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?}");

            });
        }
    }

1 Ответ

0 голосов
/ 11 июля 2020
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('Your cookie to delete name');
});
...