Pet*_*ter 12 cookies reactjs openid-connect asp.net-core identityserver4
我们有一个用 React 编写的 SPA 和用于托管的 ASP.net 核心。
为了验证应用程序,我们使用 IdentityServer4 并使用 cookie。客户端根据示例配置,这里描述:https : //github.com/IdentityServer/IdentityServer4/tree/main/samples/Quickstarts/4_JavaScriptClient/src
为了验证用户,一切正常。它将被重定向到登录页面。登录后,重定向到 SPA 就完成了。身份验证 cookie 按预期设置:
出于身份验证的原因,cookie 也用于其他 MVC(.net core 和 MVC 5)应用程序。在 SPA 中,我们还使用 SignalR,它需要 cookie 进行身份验证。
我们的问题:
在浏览器中闲置大约 30 分钟并进行刷新或导航后,身份验证 cookie(仅此而已,其他仍然存在)将自动从浏览器中消失。然后用户必须再次登录。为什么这会与 SPA 一起发生?
代码
完整代码可以在github中找到
客户
片段 UserService.ts
const openIdConnectConfig: UserManagerSettings = {
authority: baseUrls.person,
client_id: "js",
redirect_uri: joinUrl(baseUrls.spa, "signincallback"),
response_type: "code",
scope: "openid offline_access profile Person.Api Translation.Api",
post_logout_redirect_uri: baseUrls.spa,
automaticSilentRenew: true
};
export const getUserService = asFactory(() => {
const userManager = new UserManager(openIdConnectConfig);
return createInstance(createStateHandler(defaultUserState), userManager, createSignInProcess(userManager));
}, sameInstancePerSameArguments());
Run Code Online (Sandbox Code Playgroud)
服务器
剪掉了 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
Log.Information($"Start configuring services. Environment: {_environment.EnvironmentName}");
services.AddControllersWithViews();
services.AddIdentity<LoginInputModel, RoleDto>()
.AddDefaultTokenProviders();
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
if (_environment.IsDevelopment())
{
identityServerBuilder.AddDeveloperSigningCredential();
}
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(_sharedAuthTicketKeys))
.SetApplicationName("SharedCookieApp");
services.AddAsposeMailLicense(Configuration);
var optionalStartupSettings = SetupStartupSettings();
if (optionalStartupSettings.IsSome)
{
var settings = optionalStartupSettings.Value;
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new PathString("/Account/AccessDenied");
options.Cookie.Name = ".AspNetCore.Auth.Cookie";
options.Cookie.Path = "/";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.LoginPath = new PathString("/account/login");
options.Cookie.SameSite = SameSiteMode.None;
});
var authBuilder = services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Identity.Application"; });
authBuilder = ConfigureSaml2(authBuilder, settings);
authBuilder = ConfigureGoogle(authBuilder);
authBuilder.AddCookie();
}
else
{
throw new InvalidOperationException($"Startup settings are not configured in appsettings.json.");
}
SetupEntityFramework(services);
}
Run Code Online (Sandbox Code Playgroud)
身份服务器客户端配置的片段来自 appsettings.json
{
"Enabled": true,
"ClientId": "js",
"ClientName": "JavaScript Client",
"AllowedGrantTypes": [ "authorization_code" ],
"RequirePkce": true,
"RequireClientSecret": false,
"RedirectUris": [ "https://dev.myCompany.ch/i/signincallback", "https://dev.myCompany.com/i/signincallback", "https://dev.myCompany.de/i/signincallback" ],
"PostLogoutRedirectUris": [ "https://dev.myCompany.ch/i/", "https://dev.myCompany.com/i/", "https://dev.myCompany.de/i/" ],
"AllowedCorsOrigins": [],
"AllowedScopes": [ "openid", "offline_access", "profile", "Translation.Api", "Person.Api" ],
"RequireConsent": false,
"AllowOfflineAccess": true
}
Run Code Online (Sandbox Code Playgroud)
更新
与此同时,我发现 cookiehttps://ourdomain/.well-known/openid-configuration在 30 分钟空闲时间后请求时,丢失了Domain、Path、Expires/Max-Age、HttpOnly、Secure 和 SameSite.None 的值。这些值肯定是在登录后设置的。响应 cookie 的Expires/Max-Age 值设置为过去的时间,因此 cookie 将被浏览器丢弃。

有谁知道为什么这些值在一段时间后丢失了?
最后,我想出了如何解决这个问题。
这与 IdentityServer 的配置有关。缺少的部分是方法AddAspNetIdentity<LoginInputModel>()。
前:
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
Run Code Online (Sandbox Code Playgroud)
现在:
var certificate = LoadSigningCertificate();
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddSigningCredential(certificate)
.AddAspNetIdentity<LoginInputModel>()
.AddProfileService<ProfileService>()
.AddInMemoryIdentityResources(Config.Ids)
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(new ClientConfigLoader().LoadClients(Configuration));
Run Code Online (Sandbox Code Playgroud)
通过该附加配置行,Identity Server 可以正确处理 cookie。
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |