복붙노트

[REDIS] 푸른에서 ASP.NET 코어와 레디 스에 저장 사용자 세션

REDIS

푸른에서 ASP.NET 코어와 레디 스에 저장 사용자 세션

내 프로젝트에 몇 가지 물건을 저장하기위한 레디 스 캐시를 사용하고 있습니다.

나는 푸른 (웹 애플리케이션)를 사용하고, 나는 생산에 내 프리 프로덕션 환경 사이의 SWAP을 수행 할 때, 사용자 세션이 손실되고 그는 내 웹 페이지에서 다시 로그인 할 필요가있다.

나는 UseCookieAuthentication으로, 아이덴티티 3.0을 사용하고 있습니다. 나는 스왑을 수행 할 때 내 문제를 해결하기위한 레디 스에서 "세션"을 저장하고 싶습니다.

나는 어떤 아이디어으로 정보를 찾을 수 있습니까? 감사

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

            });

        }

해결법

  1. ==============================

    1.세션이 인증에 연결되지 않은, 당신은 잘못된 방법으로 그것을 해결하기 위해 시도하고 있습니다.

    세션이 인증에 연결되지 않은, 당신은 잘못된 방법으로 그것을 해결하기 위해 시도하고 있습니다.

    모든 형태의 인증 티켓 및 쿠키 암호화 및 데이터 보호 층을 사용하여 서명됩니다. 당신이 발생한 문제는되지가 저장되는 암호화 키에 기인하고, 응용 프로그램은 서로 분리된다.

    이를 해결하기 위해 당신은 모두 암호화 키를 공유하고 코드에서 응용 프로그램 이름을 설정해야합니다. 모든 정직에서 나는 그렇게하지 권하고 싶습니다. 사전 생산은 라이브 서비스하지 않고, 한 번에 모두 인증 할 수 없어야합니다.

    당신이 다음이 작업을 수행해야합니다 같은 느낌이 경우에 당신은 암호화 키 링을 공유하고, 고정 된 응용 프로그램 이름을 설정해야합니다. 당신은 공유 폴더를 통해, 또는 SQL 또는 푸른 저장 등의 공유 위치에 저장하여 키를 공유 할 수 있습니다. 당신이 IXmlRepository를 구현하여, 자신의 열쇠 고리 공급자를 작성해야 할 것이다이를 위해. 당신이 당신의 키를 공유 일단 당신은 데이터 보호 구성 중에 SetApplicationName를 사용하여 고정 된 응용 프로그램 ID를 설정할 수 있습니다.

  2. from https://stackoverflow.com/questions/36474580/save-user-session-in-redis-with-asp-net-core-in-azure by cc-by-sa and MIT license