当前位置: 首页 > 面试题库 >

使用Azure中的ASP.NET Core在Redis中保存用户会话

邵旺
2023-03-14
问题内容

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

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

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

我没有找到相关信息,有什么想法吗?谢谢

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

            });

        }

问题答案:

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

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

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

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



 类似资料:
  • 问题内容: 我最近开始在新的Azure VM上托管我的一个副项目。该应用程序将Redis用作内存缓存。在本地环境中一切正常,但是现在我已将代码移至Azure,我发现Bookleeve中出现了一些奇怪的异常。 当应用首次启动时,一切正常。但是,在闲置约5-10分钟后,对应用程序的下一个请求遇到了网络异常(我现在正在工作,并且没有确切的错误消息,因此我回到家时会张贴这些消息,如果人们认为他们与讨论密切

  • 当用户登录时,我将用户id存储到会话中,然后我希望将该用户id传递给ajax以检索数据库中的其他信息。存储在会话中的用户ID未传递给allResult。php我的登录页面代码片段,我在其中进行会话: 现在,登录后,用户将被带到仪表板: 在仪表板中,我试图使用ajax访问用户的其他数据 我需要获取用户id才能运行allResult。php所有结果。php

  • 问题内容: 我一直在研究一个网页,该网页显示我在天蓝色云中的数据库中的表。为了减少直接调用数据库以提高性能,我想为页面建立一个缓存。当前,我为表的 读取 保留了一个内存中的缓存(进程内)。现在,我要创建一个进程外缓存,该缓存应在进行 写 操作时进行更新,这意味着插入或更新(因为在更新或添加了一个值之后,内存中缓存将不再有效)。 我被推荐使用Redis,尤其是Book Sleeve,我的问题是在哪里

  • 目前,我正在使用Scala开发一个具有Play2框架的后端服务器。我有以下问题: 我使用文件处理程序GridFS在MongoDB中保存像图像这样的文档。GridFs创建两个文件: fs.files(包含元数据)和fs.chunks(存储块) 但我想把图像保存在我自己的收藏中。所有图像都应该有一个数据库条目,如用户名和注释。我有两个解决问题的办法,但我需要帮助。 使用我自己的收藏: 如何使用Grid

  • 我想将云服务部署到Azure,但在部署时必须选择存储帐户(在新门户和Visual Studio 2015中都尝试过)。我的存储帐户是使用新门户“存储帐户”创建的,并分配给了某些资源组,因此在部署时我无法选择它。对如何部署有何建议?

  • 我正在使用Spring MVC和Hibernate创建应用程序,人们可以在其中注册并将一些数据存储在他们的帐户中。我创建了注册和登录过程。现在我有一个问题,如何保留用户会话?我不想在应用程序的每个页面中保留用户ID。例如:一旦用户登录,他就会到达页面 其中id是用户的id。我希望每个登录的用户看起来像这样: 如何使用Spring在会话中保存用户数据,并在用户关闭站点然后打开站点时保存数据的最佳实践