使用Azure中的ASP.NET Core在Redis中保存用户会话 [英] Save user session in Redis with ASP.NET Core in Azure

查看:63
本文介绍了使用Azure中的ASP.NET Core在Redis中保存用户会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Redis缓存在项目中保存一些内容.

I'm using redis cache for saving some stuff in my project.

我正在使用Azure(WebApp),当我在预生产环境与生产环境之间进行SWAP时,用户会话丢失了,他需要重新登录我的网页.

I am using Azure (WebApp), and when I do a SWAP between my preproduction environment to production, the user session is lost and he need to relogin in my web page.

我正在使用Identity 3.0和UseCookieAuthentication.我想将会话"存储在Redis中,以解决交换时遇到的问题.

I'm using Identity 3.0, with UseCookieAuthentication. I would like to store the "session" in Redis for solving my problem when I do the swap.

我没有找到有关它的信息,有什么主意吗?谢谢

I don't found information about it, any ideas? Thanks

Startup.cs代码ConfigureServices:

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" });

            });

        }

推荐答案

会话未链接到身份验证,您正在尝试以错误的方式解决它.

Session is not linked to Authentication, you're attempting to solve it in the wrong way.

所有表单身份验证票证和cookie均使用数据保护层进行加密和签名.您遇到的问题是由于未保存加密密钥,并且应用程序彼此隔离.

All forms authentication tickets and cookies are encrypted and signed using the data protection layer. The problem you are encountering is due to the encryption keys not being saved, and applications being isolated from each other.

为了解决该问题,您必须共享两个加密密钥并在代码中设置一个应用程序名称.老实说,我建议你不要.试生产不是实时服务,您不应该一次对两者进行身份验证.

In order to solve it you must share both the encryption keys and set an application name in your code. In all honesty I'd recommend you don't. Pre-production is not a live service, and you shouldn't be able to authenticate to both at once.

如果您觉得必须这样做,则需要共享加密密钥环,并设置一个固定的应用程序名称.您可以通过共享文件夹或通过将密钥存储在共享位置(例如SQL或Azure存储)来共享密钥.为此,您必须编写一个自己的密钥环提供程序,方法是实施 SetApplicationName 在数据保护配置过程中.

If you feel like you must do this then you need to share the encryption key-ring, and set a fixed application name. You can share keys via a shared folder, or by storing them in a shared location, such as SQL, or Azure storage. In order to do so you'd have to write your own keyring provider, by implementing an IXmlRepository. Once you have your keys shared then you can set a fixed application identifier by using SetApplicationName during data protection configuration.

这篇关于使用Azure中的ASP.NET Core在Redis中保存用户会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆