[英]Asp.Net core “remember me” persistent cookie not works after deploy
我已經構建了一個MVC Core(Framework)應用程序,我使用Identity登錄。 當我單擊“記住我”選項時,我的開發機器上的所有內容都可以,但在服務器機器上部署之后,“記住我”在30分鍾后不會保持登錄狀態。
我試圖檢查cookie到期日期是否已設置並且似乎沒問題,同樣在服務器機器上,cookie似乎設置得很好。 您可以在下圖中看到我的Cookie詳細信息:
任何人都可以幫我解決這個問題嗎?
在此先感謝您的回復:)
編輯:
根據Orhun的要求,我在下面添加了我的Startup.cs內容:
public partial class Startup
{
public SymmetricSecurityKey signingKey;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
// For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
///////////////////////////
// Custom Services - START
///////////////////////////
string conn = CreateConnectionString(Configuration.GetConnectionString("TiesseWebConnection"));
services.AddScoped<System.Data.Entity.DbContext>((_) => new TiesseWeb.DAL.TiesseWebEntities(conn)); //Configuration["Data:DefaultConnection:ConnectionString"]));
// SESSION section
services.AddMemoryCache();
services.AddDistributedMemoryCache();
services.AddSession();
services.AddSingleton<IConfiguration>(Configuration); // IConfiguration explicitly
// Add functionality to inject IOptions<T> (important for inject Config object)
services.AddOptions();
// Add our Config object so it can be injected
services.Configure<Settings>(Configuration.GetSection("Settings"));
// Add our Config object so it can be injected
services.AddScoped<Settings>();
services.AddScoped<Tiesse.Web.BL.TiesseWebManager>();
///////////////////////////
// Custom Services - END
///////////////////////////
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TiesseWebConnection")));
services.AddIdentity<ApplicationUser, ApplicationRole>(i =>
{
i.SecurityStampValidationInterval = TimeSpan.FromDays(14);
//i.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromDays(14);
})
//services.AddIdentity<ApplicationUser, ApplicationRole>()//IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext, int>()
.AddDefaultTokenProviders();
services.AddMvc().AddJsonOptions(jsonOptions =>
{
jsonOptions.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
}); ;
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
// Adds Authorizations
services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy => policy.RequireClaim("Admin"));
options.AddPolicy("Admin-Utenti", policy => policy.RequireClaim("Admin-Utenti"));
options.AddPolicy("Admin-Filiali", policy => policy.RequireClaim("Admin-Filiali"));
options.AddPolicy("Admin-Reparti", policy => policy.RequireClaim("Admin-Reparti"));
options.AddPolicy("GoogleDrive", policy => policy.RequireClaim("GoogleDrive"));
options.AddPolicy("GoogleDrive-Gestione", policy => policy.RequireClaim("GoogleDrive-Gestione"));
options.AddPolicy("GoogleDrive-Gestione-Struttura", policy => policy.RequireClaim("GoogleDrive-Gestione-Struttura"));
options.AddPolicy("GoogleDrive-Consultazione", policy => policy.RequireClaim("GoogleDrive-Consultazione"));
options.AddPolicy("Reports", policy => policy.RequireClaim("Reports"));
options.AddPolicy("Reports-Test", policy => policy.RequireClaim("Reports-Test"));
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Custom settings
app.UseSession();
//// configures Bearer token Authentication
//ConfigureAuth(app);
///////////////////
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
//app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
//app.UseBrowserLink();
}
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
//CookieName = "MyWebCookie",
//CookieDomain = "http://devweb01:81", // uncomment when deploy
CookieHttpOnly = true,
CookieSecure = CookieSecurePolicy.Always,
ExpireTimeSpan = TimeSpan.FromDays(30),
SlidingExpiration = true,
AutomaticAuthenticate = true,
AutomaticChallenge = true
//AuthenticationScheme = "MyeWebCookie"
});
app.UseGoogleAuthentication(new GoogleOptions()
{
// following Goggle Secrets data have been hardcoded because Configuration with Secrets.json works only in development environment
ClientId = "XXXXXXX....",
ClientSecret = "XXXXXXX....",
AutomaticAuthenticate = true
//SignInScheme = "MyWebCookie"
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
#region Methods
public static string CreateConnectionString(string providerConnectionString)
{
var entityBuilder = new EntityConnectionStringBuilder();
// use your ADO.NET connection string
entityBuilder.ProviderConnectionString = providerConnectionString;
entityBuilder.Provider = "System.Data.SqlClient";
// Set the Metadata location.
entityBuilder.Metadata = @"res://*/TiesseWebDB.csdl|res://*/TiesseWebDB.ssdl|res://*/TiesseWebDB.msl";
return entityBuilder.ConnectionString;
}
#endregion
}
我遇到了同樣的問題。 我很長時間都無法解決它。 但是幾天前我找到了解決方案。 正如您在評論中提到的,問題是機器密鑰。 我不知道為什么,但應用程序每次重新啟動時都會生成新的機器密鑰。 因此解決問題的方法是強制應用程序使用常量鍵。 要做到這一點,你需要在啟動時添加這樣的代碼:
public void ConfigureServices(IServiceCollection services)
{
var environment = services.BuildServiceProvider().GetRequiredService<IHostingEnvironment>();
services.AddDataProtection()
.SetApplicationName($"my-app-{environment.EnvironmentName}")
.PersistKeysToFileSystem(new DirectoryInfo($@"{environment.ContentRootPath}\keys"));
...
}
應用程序在“key”文件夾中啟動后,您將找到包含機器密鑰的xml。 您可以在此處找到更多詳情
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.