簡體   English   中英

.NET Core 3.1 身份驗證 Cookie 在很短的時間內丟失

[英].NET Core 3.1 Authentication Cookie Lost After Very Short Time

該項目仍在開發中,在我的開發筆記本電腦上運行良好,但是,當我發布到我的共享托管 Web 服務器 (Winserve) 時,功能就會中斷。

旁注:我確定這在幾周前運行良好,但我可能是錯的,因為我大部分時間都在我的開發筆記本電腦上運行它。

我有一個基本的 asp.net Core 3.1 Web 應用程序。 我已將 Cookie 和身份驗證信息添加到我的 startup.cs 文件中的 Configure() 和 ConfigureServices() 部分。

我可以登錄到 PROD 中的應用程序,我的 auth cookie 似乎設置正確,它正確地從數據庫中獲取角色並添加相關聲明等,並為用戶提供正確的角色。 我知道這是因為 UI 會根據 User.Identity.IsAuthenticated = true 以及 User.IsInRole("Some Role") 等是否發生變化。

但是,經過一段(不一致的)時間后,通常大約 30-40 秒,當我導航到需要對用戶進行身份驗證(具有 [Authorize] 資格)的頁面(控制器/操作)時,我被重定向回登錄頁面! 但這不僅僅是重定向,用戶已被注銷或 cookie 不再有效。 我每 5 秒嘗試一次,持續大約 30 秒,在這碰巧返回“授權”URL 並且每次我被推回登錄頁面時。

在那段時間內(在 30-40 秒之前),我可以導航到受保護的頁面,找到我的心聲。 所有不同的頁面,要么一個接一個,要么在導航之間留幾秒鍾的間隔,它仍然可以工作,直到它不工作為止!

此外,我已經在瀏覽器檢查器中檢查了 Cookie,並且肯定會創建 Cookie,我認為它的默認到期日期約為 14 天。 但無論如何,這都是未來的道路。

這是我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews().AddRazorRuntimeCompilation().AddNewtonsoftJson();

            services.AddControllers().AddNewtonsoftJson();

            services.AddDistributedMemoryCache();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie(options =>
                                {
                                    options.LoginPath = "/Login";
                                });

            services.AddAuthorization();

            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

            services.AddMvc().AddNewtonsoftJson();

            services.AddRazorPages().AddNewtonsoftJson();

        }

        // 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");
                // 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.UseRouting();

            app.UseSession();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseHttpsRedirection();

            app.UseStaticFiles();

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

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

        }

這是我的 HomeController 中的登錄和注銷方法...

public IActionResult Login(LoginViewModel model)
        {
            if (string.IsNullOrEmpty(model.Username) || string.IsNullOrEmpty(model.Password)) { model.Errors.Add("Must provide a Username & Password"); return View(model); }
            var _user = _authenticationBusinessService.AuthenticateUser(model.Username, model.Password);
            if (_user != null && _user.Id > 0) { return SignUserIn(model, _user); }
            else { model.Errors.Add("We're unable to authenticate you with the credentials provided"); }
            return View(model);
        }

        public IActionResult SignOut()
        {
            return SignUserOut();
        }

他們調用的方法......

   private IActionResult SignUserIn(LoginViewModel model, UserDTO user)
        {
            var _claims = new List<Claim>
            {
                //User identity information
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Id.ToString()),
                new Claim("FirstName", user.Person.FirstName),
                new Claim("Surname", user.Person.Surname)
            };
            //Roles/Permissions
            _claims.AddRange(user.UserPermissionMaps.Select(x => new Claim(ClaimTypes.Role, x.Permission.Description)));

            var _claimsIdenity = new ClaimsIdentity(_claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var _authProperties = new AuthenticationProperties() { IsPersistent = true, AllowRefresh = true };
            var _claimsPrincipal = new ClaimsPrincipal(_claimsIdenity);
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, _claimsPrincipal, _authProperties);

            if (string.IsNullOrEmpty(model.ReturnURL))
            {
                model.ReturnURL = "/";
            }
            return Redirect(model.ReturnURL);
        }
        private IActionResult SignUserOut()
        {
            HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.Session.Clear();
            return RedirectToAction("Index");
        }

您需要獲得授權才能訪問的示例控制器...

 [Area("Admin")]
    public class HomeController : Controller
    {
        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
    }

感謝@weichch,我找到了問題的解決方案

我的廉價托管服務提供商設置了 200MB 的 AppPool 大小限制

我的應用程序,當通過 VS 通過 IIS Express 加載時,達到 160-180MB 左右,然后相當快,(例如,只需在我的管理部分做一些事情),超過 200MB,但然后坐在 220-230MB 左右,並沒有並沒有真正移動(所以這不是內存泄漏問題)。

我與我的提供商將我的計划升級到 AppPool 可以達到 512MB 的計划,這完全解決了問題。 從那以后它一直運行良好。

謝謝大家👍

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM