使用 Azure 中的 ASP.NET Core 在 Redis 中保存用户会话
Save user session in Redis with ASP.NET Core in Azure
我正在使用 Redis 缓存来保存项目中的一些内容。
我正在使用 Azure (WebApp),当我在预生产环境和生产环境之间进行交换时,用户会话丢失,他需要重新登录我的网页。
我正在使用带有 UseCookieAuthentication 的 Identity 3.0。我想将 "session" 存储在 Redis 中,以解决我在交换时遇到的问题。
我没有找到相关信息,有什么想法吗?谢谢
Startup.cs代码配置服务:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
// Registers MongoDB conventions for ignoring default and blank fields
// NOTE: if you have registered default conventions elsewhere, probably don't need to do this
//RegisterClassMap<ApplicationUser, IdentityRole, ObjectId>.Init();
AutoMapperWebConfiguration.Configure();
services.AddSingleton<ApplicationDbContext>();
// Add Mongo Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(o =>
{
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonLetterOrDigit = false;
o.Password.RequiredLength = 6;
o.User.RequireUniqueEmail = true;
o.Cookies.ApplicationCookie.CookieSecure = CookieSecureOption.SameAsRequest;
o.Cookies.ApplicationCookie.CookieName = "MyCookie";
})
.AddMongoStores<ApplicationDbContext, ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.CookieName = "MyCookie";
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddLocalization(options => options.ResourcesPath = "Resources");
// Caching This will add the Redis implementation of IDistributedCache
services.AddRedisCache();
services.Configure<RedisCacheOptions>(options =>
{
options.Configuration = Configuration["RedisConnection"];
});
services.AddCaching();
// Add MVC services to the services container.
services.AddMvc(options =>
{
options.CacheProfiles.Add("OneDay",
new CacheProfile()
{
Duration = 86400,
Location = ResponseCacheLocation.Any
});
options.CacheProfiles.Add("OneMinute",
new CacheProfile()
{
Duration = 60,
Location = ResponseCacheLocation.Any
});
})
.AddViewLocalization(options => options.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization();
services.Configure<AppOptions>(Configuration.GetSection("AppOptions"));
}
Startup.cs代码
// 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)
{
//
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.LoginPath = new PathString("/Account/Login");
options.AutomaticChallenge = true;
});
var requestLocalizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
},
RequestCultureProviders = new List<IRequestCultureProvider>
{
new CookieRequestCultureProvider
{
CookieName = "_cultureLocalization"
},
new QueryStringRequestCultureProvider(),
new AcceptLanguageHeaderRequestCultureProvider
{
}
}
};
app.UseRequestLocalization(requestLocalizationOptions, defaultRequestCulture: new RequestCulture("en-US"));
app.UseFacebookAuthentication(options =>
{
options.AppId = "*****";
options.AppSecret = "****";
});
app.UseGoogleAuthentication(options =>
{
options.ClientId = "*****";
options.ClientSecret = "***";
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "view",
template: "{customName}/{id}",
defaults: new { controller = "View", action = "Index" });
});
}
会话未链接到身份验证,您试图以错误的方式解决它。
所有表单身份验证票和 cookie 都使用数据保护层进行加密和签名。您遇到的问题是由于加密密钥未保存,应用程序相互隔离所致。
为了解决这个问题,您必须共享两个加密密钥并在您的代码中设置一个应用程序名称。老实说,我建议你不要。预生产不是实时服务,您不应该同时对两者进行身份验证。
如果您觉得必须这样做,那么您需要共享加密密钥环,并设置一个固定的应用程序名称。您可以通过共享文件夹共享密钥,或将它们存储在共享位置,例如 SQL,或 Azure 存储。为此,您必须通过在数据保护配置期间实施 IXmlRepository. Once you have your keys shared then you can set a fixed application identifier by using SetApplicationName 来编写自己的密钥环提供程序。
我正在使用 Redis 缓存来保存项目中的一些内容。
我正在使用 Azure (WebApp),当我在预生产环境和生产环境之间进行交换时,用户会话丢失,他需要重新登录我的网页。
我正在使用带有 UseCookieAuthentication 的 Identity 3.0。我想将 "session" 存储在 Redis 中,以解决我在交换时遇到的问题。
我没有找到相关信息,有什么想法吗?谢谢
Startup.cs代码配置服务:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
// Registers MongoDB conventions for ignoring default and blank fields
// NOTE: if you have registered default conventions elsewhere, probably don't need to do this
//RegisterClassMap<ApplicationUser, IdentityRole, ObjectId>.Init();
AutoMapperWebConfiguration.Configure();
services.AddSingleton<ApplicationDbContext>();
// Add Mongo Identity services to the services container.
services.AddIdentity<ApplicationUser, IdentityRole>(o =>
{
// configure identity options
o.Password.RequireDigit = false;
o.Password.RequireLowercase = false;
o.Password.RequireUppercase = false;
o.Password.RequireNonLetterOrDigit = false;
o.Password.RequiredLength = 6;
o.User.RequireUniqueEmail = true;
o.Cookies.ApplicationCookie.CookieSecure = CookieSecureOption.SameAsRequest;
o.Cookies.ApplicationCookie.CookieName = "MyCookie";
})
.AddMongoStores<ApplicationDbContext, ApplicationUser, IdentityRole>()
.AddDefaultTokenProviders();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60);
options.CookieName = "MyCookie";
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddLocalization(options => options.ResourcesPath = "Resources");
// Caching This will add the Redis implementation of IDistributedCache
services.AddRedisCache();
services.Configure<RedisCacheOptions>(options =>
{
options.Configuration = Configuration["RedisConnection"];
});
services.AddCaching();
// Add MVC services to the services container.
services.AddMvc(options =>
{
options.CacheProfiles.Add("OneDay",
new CacheProfile()
{
Duration = 86400,
Location = ResponseCacheLocation.Any
});
options.CacheProfiles.Add("OneMinute",
new CacheProfile()
{
Duration = 60,
Location = ResponseCacheLocation.Any
});
})
.AddViewLocalization(options => options.ResourcesPath = "Resources")
.AddDataAnnotationsLocalization();
services.Configure<AppOptions>(Configuration.GetSection("AppOptions"));
}
Startup.cs代码
// 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)
{
//
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseApplicationInsightsExceptionTelemetry();
app.UseStaticFiles();
app.UseIdentity();
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.LoginPath = new PathString("/Account/Login");
options.AutomaticChallenge = true;
});
var requestLocalizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("es-ES")
},
RequestCultureProviders = new List<IRequestCultureProvider>
{
new CookieRequestCultureProvider
{
CookieName = "_cultureLocalization"
},
new QueryStringRequestCultureProvider(),
new AcceptLanguageHeaderRequestCultureProvider
{
}
}
};
app.UseRequestLocalization(requestLocalizationOptions, defaultRequestCulture: new RequestCulture("en-US"));
app.UseFacebookAuthentication(options =>
{
options.AppId = "*****";
options.AppSecret = "****";
});
app.UseGoogleAuthentication(options =>
{
options.ClientId = "*****";
options.ClientSecret = "***";
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "view",
template: "{customName}/{id}",
defaults: new { controller = "View", action = "Index" });
});
}
会话未链接到身份验证,您试图以错误的方式解决它。
所有表单身份验证票和 cookie 都使用数据保护层进行加密和签名。您遇到的问题是由于加密密钥未保存,应用程序相互隔离所致。
为了解决这个问题,您必须共享两个加密密钥并在您的代码中设置一个应用程序名称。老实说,我建议你不要。预生产不是实时服务,您不应该同时对两者进行身份验证。
如果您觉得必须这样做,那么您需要共享加密密钥环,并设置一个固定的应用程序名称。您可以通过共享文件夹共享密钥,或将它们存储在共享位置,例如 SQL,或 Azure 存储。为此,您必须通过在数据保护配置期间实施 IXmlRepository. Once you have your keys shared then you can set a fixed application identifier by using SetApplicationName 来编写自己的密钥环提供程序。