微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ASP.NET Core Web App 被迫频繁登录

如何解决ASP.NET Core Web App 被迫频繁登录

我有一个使用 ASP.NET Identity 进行身份验证的 ASP.NET Core 3.1 Web 应用程序。当我在本地运行它时一切正常,但是当我部署到托管服务提供商时,我发现用户经常被要求登录(仅在几分钟不活动后)。我此时的猜测是,时机与应用程序池回收有关,因为我可以通过手动回收应用程序池来强制登录。不幸的是,我无法控制服务器上的应用程序池设置 - 空闲超时设置为 5 分钟。

如果我了解 ASP.NET Identity(这可能是一个延伸),身份验证令牌存储在 cookie 中并随每个请求传输。我看不出应用程序池回收对验证该 cookie 有何影响。如果它以会话状态存储在服务器上,我可以看到这种情况发生,但我认为这不会发生。

我的 ConfigureServices 方法非常有用,除此之外,我向标准 User 和 Role 对象添加了一些字段。

public void ConfigureServices(IServiceCollection services) {
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMysqL(Configuration.GetConnectionString("DefaultConnection"))
    );

    services.AddIdentity<User,Role>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.Configure<IdentityOptions>(options => {
        options.Password.requiredigit = true;
        options.Password.RequireLowercase = true;
        options.Password.RequireNonAlphanumeric = false;
        options.Password.RequireUppercase = true;
        options.Password.requiredLength = 8;

        options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
        options.Lockout.MaxFailedAccessAttempts = 5;
        options.Lockout.AllowedForNewUsers = true;

        options.SignIn.RequireConfirmedEmail = true;
        options.SignIn.RequireConfirmedPhoneNumber = false;

        options.User.RequireUniqueEmail = false;
    });

    services.ConfigureApplicationCookie(options => {
        options.Cookie.HttpOnly = true;
        options.Cookie.SameSite = SameSiteMode.Lax;
        options.AccessDeniedpath = "/Identity/Account/AccessDenied";
        options.LoginPath = "/Identity/Account/Login";
        options.ExpireTimeSpan = TimeSpan.FromDays(30);
        options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
        options.SlidingExpiration = true;
    });

    services.AddScoped<IUserClaimsPrincipalFactory<User>,ApplicationUserClaimsPrincipalFactory>();

    services.AddSingleton<IEmailService,EmailService>();
    services.AddTransient<DatabaseInitializationHelper>();

    services.AddControllersWithViews();
    services.AddRazorPages();

    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddOptions<CaptchaSettings>().Bind(Configuration.GetSection("Captcha"));
    services.AddTransient<CaptchaVerificationService>();
}

Configure 方法也非常标准。

public void Configure(IApplicationBuilder app,IWebHostEnvironment env) {
    if (env.IsDevelopment() || env.EnvironmentName == "Dev") {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
    }
    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.UseCookiePolicy();

    app.UseRouting();

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

    //app.UseSession();

    app.UseEndpoints(endpoints => {

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

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

        endpoints.MapControllerRoute(
            name: "api",pattern: "_api/{controller}/{id?}");
        endpoints.MapRazorPages();
    });
}

这可能与应用程序池回收有关吗?如果是这样,有什么方法可以在不访问应用程序池设置的情况下解决这个问题?如果没有,还有什么可能导致它?

解决方法

原来这与数据保护有关,我可以使用 this answer 解决它。显然,我的托管服务提供商限制了最终阻止访问通常存储此类信息的位置的权限。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。