string redisConnectionString = Configuration.GetSection("Storage:Redis").GetValue<string>("ConnectionString"); string redisInstanceName = Configuration.GetSection("Storage:Redis").GetValue<string>("InstanceName"); services.AddDistributedRedisCache(options => { options.Configuration = $"{redisConnectionString},defaultDataBase=0"; options.InstanceName = redisInstanceName; }); IDataProtectionBuilder dataProtectionBuilder = services.AddDataProtection() .SetApplicationName("XXX") .UseCryptographicAlgorithms( new AuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256 }) .PersistKeysToRedis(ConnectionMultiplexer.Connect($"{redisConnectionString},defaultDataBase=0"), "XXX-DataProtection-Keys"); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(20); //session活期时间 options.Cookie = new CookieBuilder() { Name = $".{GetType().Namespace}.Session", HttpOnly = true, }; }); services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));//中文乱码 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.DataProtectionProvider = CreateRedisDataProtectionProvider(ConnectionMultiplexer.Connect($"{redisConnectionString},defaultDataBase=1")); //options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\_sso")); options.SlidingExpiration = true; options.LoginPath = "/account/signin"; options.Cookie = new CookieBuilder() { HttpOnly = true, Name = $".{GetType().Namespace}", }; });
IDataProtectionProvider CreateRedisDataProtectionProvider(IConnectionMultiplexer connection) { return new ServiceCollection() .AddDataProtection() .SetApplicationName("XXX.SSO") .UseCryptographicAlgorithms( new AuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256 }) .PersistKeysToRedis(connection, "XXX-SSO-DataProtection-Keys") .Services .BuildServiceProvider() .GetRequiredService<IDataProtectionProvider>(); }
app.UseAuthentication(); app.UseSession();//在UseMvc前面 app.UseMvc();