刷新身份验证cookie以避免注销

时间:2018-10-31 14:21:31

标签: c# asp.net-identity asp.net-core-2.0 session-cookies

我正在使用带有Identity的ASP.NET Core 2.0应用程序来管理用户连接。

我有一些自定义的Manager,Store和Providers用于我的应用程序需求:

NotifyOfPropertyChange(() => MyText);

我已经为身份验证设置了应用程序Cookie:

services.AddIdentity<Utilisateur, Profil>().AddUserManager<CustomUserManager<Utilisateur>>().AddRoleManager<CustomRoleManager>().AddDefaultTokenProviders();
services.AddTransient<IUserStore<Utilisateur>, UserStore>();
services.AddTransient<IRoleStore<Profil>, ProfileStore>();
services.AddTransient<IPermissionProvider, PermissionProvider>();

还有

app.UseAuthentication();

问题在于,即使用户不闲着并在此时使用该应用程序,它也会在30分钟后自动断开连接。

如何刷新或重新创建身份验证cookie以避免出现此问题?

我试图创建一种刷新cookie的方法,但是它似乎不能很好地工作……即使这样,用户也已断开连接。

services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
            // If the LoginPath isn't set, ASP.NET Core defaults the path to /Account/Login.
            options.LoginPath = new PathString("/Connexion/Login");
            options.LogoutPath = new PathString("/Connexion/SignedOut");
            // If the AccessDeniedPath isn't set, ASP.NET Core defaults the path to /Account/AccessDenied.
            options.AccessDeniedPath = new PathString("/Connexion/AccessDenied");
            options.SlidingExpiration = true;
        });

和方法:

    [HttpPost]
    [RefreshLogin]
    [RequiresPermission("Pages.Modification")]
    public IActionResult SavePagesOrder() 
    {...}

您有解决我问题的想法吗?

1 个答案:

答案 0 :(得分:0)

这是我与IdentityServer 4一起使用的解决方案。抱歉,它可能很凌乱,但我希望您能理解这一点。每次您验证主体时,都可以在这里重写访问权限并将令牌刷新为cookie。

services.AddAuthentication(options =>
                {
                    options.DefaultScheme = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
                {
                    options.Events = new CookieAuthenticationEvents
                    {
                        OnValidatePrincipal = async x =>
                        {
                            var now = DateTimeOffset.UtcNow;
                            var timeElapsed = now.Subtract(x.Properties.IssuedUtc.Value);
                            var timeRemaining = x.Properties.ExpiresUtc.Value.Subtract(now);

                            if (timeElapsed > timeRemaining)
                            {
                                var discoveryResponse = await DiscoveryClient.GetAsync(gatewaySettings.IdentitySeverAddress);
                                if (discoveryResponse.IsError)
                                {
                                    throw new Exception(discoveryResponse.Error);
                                }

                                var identity = (ClaimsIdentity) x.Principal.Identity;
                                var accessTokenClaim = identity.FindFirst("access_token");
                                var refreshTokenClaim = identity.FindFirst("refresh_token");

                                var tokenClient = new TokenClient(discoveryResponse.TokenEndpoint, "MyApi", "secret");

                                var refreshToken = refreshTokenClaim.Value;

                                var tokenResponse = await tokenClient.RequestRefreshTokenAsync(refreshToken);

                                if (!tokenResponse.IsError)
                                {
                                    identity.RemoveClaim(accessTokenClaim);
                                    identity.RemoveClaim(refreshTokenClaim);

                                    identity.AddClaims(new[]
                                    {
                                        new Claim("access_token", tokenResponse.AccessToken),
                                        new Claim("refresh_token", tokenResponse.RefreshToken)
                                    });
                                    x.ShouldRenew = true;
                                }
                            }
                        }
                    };
                })

也许会对您有所帮助。