![](/img/trans.png)
[英]Add session timeout from controller in ASP.NET Core MVC
[英]Asp.Net Core 2 MVC Authentication: Add different session times
我是一般編碼的新手,特別是 Asp.Net 核心,所以請原諒我的笨拙。 我真的希望對我的項目有所幫助。 我現在正在為不同的用戶添加不同的時間TimeSpan
在登錄時撕裂我的頭發。例如,來自公司 1 的用戶登錄,並且希望獲得 60 分鍾的會話時間(即空閑時間),但是當來自公司 2 的用戶登錄會話時間可能是默認的 20 分鍾。
更新:我的目標框架是.Net Framework 4.6.1,但代碼是為.Net Core 2.1准備的,我正在運行身份包 v2.1.2
我的startup
類看起來像這樣:
public class Startup
{
public Startup(IHostingEnvironment env)
{
CultureInfo.CurrentCulture = new CultureInfo("sv-SE");
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
builder.AddInMemoryCollection(GetBeanstalkEnvironmentProperties());
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfiguration>(Configuration);
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ExternalServerConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<EmailConfiguration>(Configuration.GetSection("EmailConfiguration"));
services.AddMvc();
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
登錄控制器就像這樣簡單:
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation(1, "User logged in.");
return RedirectToAction("...");
...
在檢查了不同的解決方案和論壇后,發現此選項可在Startup
添加Timespan
:
services.Configure<SecurityStampValidatorOptions>(options =>
{
// Add validationinterval E.g how often the stamp is checked.
options.ValidationInterval = TimeSpan.FromSeconds(10);
});
services.AddAuthentication().Services.ConfigureApplicationCookie(options =>
{
// Timespan extension if page is refreshed or navigated. Default is true.
options.SlidingExpiration = true;
// Cookie is valid at minimum 20 min.
options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
});
這工作正常,但這是為用戶設置會話時間的全局方式,然后將應用於所有用戶。 所以我希望有人有一個很好的解決方案,我可以使用上面的方法,並且仍然可以在這里添加不同的值options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
取決於用戶的偏好,例如用戶是哪家公司的成員。
其他參考資料以及我迄今為止嘗試過的內容。
我試圖解決這個問題,但在我的案例中沒有成功。 我想我首先需要能夠檢查用戶的聲明(以查看用戶屬於哪家公司),並可能為特定公司設置一個值,例如數據庫表中的公司 1值 60,然后讀取該值並更新Timespan
與來自 Db 的值或更“丑陋”的方式只是硬編碼Startup
的值。 假設用戶屬於某個公司,該公司應該有一個特定的會話值,或者如果沒有設置默認值 20 分鍾。 例如在偽:(如果 user.companyID 等於 1 然后設置 options.ExpireTimeSpan = TimeSpan.FromMinutes(60)) 等等。 我的問題是,當然我不能在啟動時訪問這個值,可能不應該?
我也試過這個,但是如果我沒有弄錯並且不會影響空閑的用戶時間,它會擴展客戶端的 cookie?! 並且它還使用 Session,我想我可以添加它,但我不確定這對我的情況是否有任何好處。
我也嘗試盡可能多地遵循此文檔。 但是該框架似乎不支持多個/不同的ExpireTimeSpan
設置。
這是另一個問題,還沒有答案,我可以告訴我遇到的相同問題。
我是這樣解決的:
services.Configure<SecurityStampValidatorOptions>(Configuration.GetSection("SecurityStampValidatorOptions"));
services.AddAuthentication().Services.ConfigureApplicationCookie(options =>
{
var cookieAuthenticationOptions = Configuration
.GetSection(nameof(CookieAuthenticationOptions))
.Get<CookieAuthenticationOptions>();
if (cookieAuthenticationOptions == null)
return;
options.ExpireTimeSpan = cookieAuthenticationOptions.ExpireTimeSpan;
options.SlidingExpiration = cookieAuthenticationOptions.SlidingExpiration;
});
也許不是最好的方式,但后來我仍然可以使用Services.ConfigureApplicationCookie
選項再加上能重寫SecurityStampValidatorOptions
和部分CookieAuthenticationOptions
從設置(appsettings.json,ENV等),由我可以部署使用不同的設置應用程序。
我無法找到如何直接從配置部分配置應用程序 cookie,因此如果設置可用,則會設置選定的幾個屬性。
所以它沒有解決我真正的問題,但這已經足夠了,因為我有不同的部署選項和位置,所以它是一個有效的走動。
然后我可以在appsettings.json
為 exempel 做這樣的appsettings.json
:
"SecurityStampValidatorOptions": {
"ValidationInterval": "0.00:00:20"
},
"CookieAuthenticationOptions": {
"SlidingExpiration": true,
"ExpireTimeSpan": "0.02:00:00"
}
並覆蓋默認值,而且在前期是Startup
中沒有硬編碼值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.