AYHAN
AYHAN

Reputation: 11

Logs User Out, Before I Tell It To

I have problem with asp.net core identity in web farm. when user logs in website an authentication cookie set in browser it works correctly in localhost but in the web farm after a little time ,for example 2 minutes, this cookie expire and user logs out , however I set expire time more than 30 days !

In asp.net MVC this problem solves while setting a machine key in Web config but in asp.net core I don`t know the answer.

Please help me thank you

            services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;

        }).AddCookie(options =>
        {
            options.Cookie.Name = "eShop_Authentication";
            options.ExpireTimeSpan = TimeSpan.FromDays(30);
            options.LoginPath = "/auth/sign-in";
            options.LogoutPath = "/auth/sign-out";
        });

and account controller - login Action

                // TODO ---> Set Authentication Cookie

                var claims = new List<Claim>()
                {
                    new Claim(ClaimTypes.NameIdentifier , user.UserId.ToString()),
                    new Claim(ClaimTypes.Name , user.UserName)
                };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var principal = new ClaimsPrincipal(identity);

                var properties = new Microsoft.AspNetCore.Authentication.AuthenticationProperties()
                {
                    IsPersistent = login.RememberMe,
                    AllowRefresh = true,
                    ExpiresUtc = DateTimeOffset.Now.AddDays(30),
                };

                HttpContext.SignInAsync
                    (CookieAuthenticationDefaults.AuthenticationScheme,principal,properties);

Upvotes: 0

Views: 112

Answers (1)

AYHAN
AYHAN

Reputation: 11

Finally I Fixed it with this code on startup

            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/Keys")));

Upvotes: 1

Related Questions