如何为Blazor WebAssembly和IdentityServer 4配置持久登录?



我们有一个独立的Blazor WebAssembly应用程序(PWA),用户需要通过IdentityServer 4(默认设置)进行身份验证(OIDC)。IdentityServer然后返回一个访问令牌,应用程序使用它来调用几个api。大多数用户在移动设备上使用该应用程序,一旦收到通知(每小时一次或两次),就需要使用该应用程序。一切都运行得很好,但是由于用户的登录不会在白天持续存在,因此他们需要每天多次重新验证自己。对于用户来说,这是非常恼人的行为。因此,我正在寻找一种解决方案,其中用户登录被持久保存至少x小时。我读了几个博客,并试图改变IdentityServer的设置,但我似乎就是无法改变这种行为。

实际行为:

  • 当用户的会话被关闭时,该用户被注销,需要在IdentityServer上重新登录。
  • 大约1小时后,用户将以任何方式注销。

预期行为:

  • 用户的登录在多个会话中持久化,例如总时间为x小时(我实际上不知道这是否可能?)
  • 只要用户登录并且应用程序处于活动状态(在后台),用户就保持身份验证。

如果用户只要使用该应用程序就保持身份验证,那么它已经有很大帮助。然而,唯一具有1小时值的设置(我可以在IdentityServer中找到)是访问令牌生命周期,默认为3600秒。但是,我也读到,这与用户必须重新验证自己的问题无关。

我想我忽略了一些东西,但我就是不知道如何解决这个问题。任何帮助都是感激的!

在我的Blazor WebAssembly项目中,我在Program.cs

中有以下配置
builder.Services.AddOidcAuthentication(options =>
{
builder.Configuration.Bind("IdentityService", options.ProviderOptions);
});
And in appsettings.json:
"IdentityService": {
"Authority": "https://localhost:44362",
"ClientId": "MyBlazorClient",
"DefaultScopes": [
"openid",
"profile",
"claims",
"roles"
],
"ResponseType": "code"
},

在IdentityServer我得到以下在我的StartUp.cs

var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.UserInteraction.LoginUrl = "/Account/Login";
options.UserInteraction.LogoutUrl = "/Account/Logout";
options.Authentication = new AuthenticationOptions()
{
CookieLifetime = TimeSpan.FromHours(8), 
CookieSlidingExpiration = true
};
})

最后,这是我在IdentityServer中的客户端配置:

new Client
{
ClientId = "MyBlazorClient",
ClientName = "My Blazor Client Application",
RequireClientSecret = false,
AllowedCorsOrigins = { https://localhost:443 },
AllowedGrantTypes = GrantTypes.Code,
RedirectUris = { "https://localhost:443/authentication/login-callback" },
PostLogoutRedirectUris = { "https://localhost:443/authentication/logout-callback" },
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"roles",
"claims"
},
RequirePkce = true,
AllowPlainTextPkce = false,
},

您可以用Startup.cs文件和所有身份/身份验证配置更新问题吗?

有可能您没有设置身份服务器将尊重的应用程序Cookie。下面是一个例子:

services.ConfigureApplicationCookie(options =>
{
options.Cookie.Name = "MyAppCookie";
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = SameSiteMode.Strict;
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.Cookie.MaxAge = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
options.LoginPath = "/login";
options.LogoutPath = "/logout";
options.AccessDeniedPath = "/error";
options.ReturnUrlParameter = CookieAuthenticationDefaults.ReturnUrlParameter;
});

最新更新