首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >刷新身份认证cookie,避免注销

刷新身份认证cookie,避免注销
EN

Stack Overflow用户
提问于 2018-10-31 22:21:31
回答 1查看 1.1K关注 0票数 1

我正在开发一个带有标识的ASP.NET Core2.0应用程序来管理用户连接。

我有一些自定义的管理器、Store和Provider来满足我的应用程序的需要:

代码语言:javascript
复制
services.AddIdentity<Utilisateur, Profil>().AddUserManager<CustomUserManager<Utilisateur>>().AddRoleManager<CustomRoleManager>().AddDefaultTokenProviders();
services.AddTransient<IUserStore<Utilisateur>, UserStore>();
services.AddTransient<IRoleStore<Profil>, ProfileStore>();
services.AddTransient<IPermissionProvider, PermissionProvider>();

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

代码语言:javascript
复制
app.UseAuthentication();

代码语言:javascript
复制
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;
        });

问题是,用户在30分钟后自动断开连接,即使他不是空闲的,并且此时正在使用应用程序。

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

我试图创建一个方法来刷新cookie,但似乎效果不是很好……即使这样,用户也会断开连接。

代码语言:javascript
复制
    [HttpPost]
    [RefreshLogin]
    [RequiresPermission("Pages.Modification")]
    public IActionResult SavePagesOrder() 
    {...}

所述方法:

代码语言:javascript
复制
public class RefreshLoginAttribute : Microsoft.AspNetCore.Mvc.Filters.ActionFilterAttribute
{
    public override async Task OnActionExecutionAsync(Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext context, Microsoft.AspNetCore.Mvc.Filters.ActionExecutionDelegate next)
    {
        await context.HttpContext.RefreshLoginAsync();

        await next();
    }
}

你有办法解决我的问题吗?

EN

回答 1

Stack Overflow用户

发布于 2018-10-31 22:53:59

这是我在IdentityServer 4上使用的解决方案。抱歉,它可能会很混乱,但我希望你能理解这一点。在这里,每次验证主体时,都可以将访问和刷新令牌重写到cookie中。

代码语言:javascript
复制
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;
                                }
                            }
                        }
                    };
                })

也许它能以某种方式帮助你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53085591

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档