首页 > 解决方案 > Identity Server 4 + Angular - 在给定时间内不活动时需要新登录

问题描述

我有一个使用 Angular 运行的 Web 应用程序,并通过 .NET Core 和 Identity Server 4 完成了身份验证。我需要实现一些非常简单的东西,但我无法在我需要的时候让它工作。所以我需要的是:如果用户正在积极使用网络应用程序,请让他们保持登录状态,但如果他们在 15 分钟内处于非活动状态,则结束会话并要求重新登录。

这就是我所拥有的:

客户端定义

new Client {
                    ClientId = "Portal",
                    ClientName = "main web application",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AccessTokenType = AccessTokenType.Reference,
                    AllowAccessTokensViaBrowser = true,
                    AlwaysIncludeUserClaimsInIdToken = true,
                    IdentityTokenLifetime = 120,
                    AccessTokenLifetime = 120,
                    RefreshTokenUsage = TokenUsage.OneTimeOnly,
                    RefreshTokenExpiration = TokenExpiration.Sliding,
                    UpdateAccessTokenClaimsOnRefresh = true,
                    RequireConsent = false,
                    RedirectUris = new List<string>(),
                    PostLogoutRedirectUris = new List<string>(),
                    AllowedCorsOrigins = new List<string>(),
                    AllowedScopes =
                        {
                            IdentityServerConstants.StandardScopes.OpenId,
                            "user",
                            "permissions",
                             // other scopes
                        }
                }

身份服务器选项

var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents = true;
                options.Events.RaiseSuccessEvents = true;

                options.Authentication.CookieAuthenticationScheme = IdentityServerConstants.DefaultCookieAuthenticationScheme;
                options.Authentication.CookieLifetime = TimeSpan.FromMinutes(1);
                options.Authentication.CookieSlidingExpiration = true;

                options.Endpoints.EnableDeviceAuthorizationEndpoint = false;
                options.Endpoints.EnableTokenRevocationEndpoint = false;
                options.Endpoints.EnableUserInfoEndpoint = false;
            });

登录代码

AuthenticationProperties props = new AuthenticationProperties
            {
                IsPersistent = false,
                ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromSeconds(120))

            };

            await httpContext.SignInAsync(user.Id.ToString(), user.UserName, props);

注意:出于测试目的,我将过期时间设置为 2 分钟而不是 15 分钟。

所以这让用户保持登录状态,但只要会话没有手动关闭(浏览器关闭),它就会让用户保持身份验证。即使在完全没有任何活动的时间到期后,它也不会要求重新登录。

调查这个问题,我发现这个问题有一个类似的场景。所以我尝试了将UserSsoLifetime属性添加到客户端定义的建议方法,但是,虽然它确实在时间到期后强制重新登录,但问题是它总是强制用户退出,即使他们是活动的。

所以我找不到中间立场。即使在非活动状态下,它也可以让用户在整个会话中保持登录状态,或者即使在活动状态下也会强制注销。我想它一定是我缺少的一些简单的东西,但它的配置太多了,老实说,我完全迷失了。

我很感激任何帮助!

标签: c#.net-coreidentityserver4

解决方案


推荐阅读