1. 程式人生 > >.net core cookie登錄和session的 DataProtectionProvider 加入 redis

.net core cookie登錄和session的 DataProtectionProvider 加入 redis

new bsp storage ogr pro section get algorithm apr

                string redisConnectionString = Configuration.GetSection("Storage:Redis").GetValue<string>("ConnectionString");
                string redisInstanceName = Configuration.GetSection("Storage:Redis").GetValue<string>("InstanceName");
                services.AddDistributedRedisCache(options 
=> { options.Configuration = redisConnectionString; options.InstanceName = redisInstanceName; }); IDataProtectionBuilder dataProtectionBuilder = services.AddDataProtection() .SetApplicationName(
"xxx") .UseCryptographicAlgorithms( new AuthenticatedEncryptorConfiguration() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256 }) .PersistKeysToRedis(ConnectionMultiplexer.Connect(redisConnectionString),
"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)); //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("Survey.SSO")
                .UseCryptographicAlgorithms(
                    new AuthenticatedEncryptorConfiguration()
                    {
                        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
                    })
                .PersistKeysToRedis(connection, "DataProtection-SSO-Keys")
                .Services
                .BuildServiceProvider()
                .GetRequiredService<IDataProtectionProvider>();
        }

                app.UseAuthentication();
                app.UseSession();//在UseMvc前面
                app.UseMvc();

.net core cookie登錄和session的 DataProtectionProvider 加入 redis