我使用 Identity Server 和 .Net 6。配置身份验证:
services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.ReturnUrlParameter = "requestedUrl";
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.Authority = "IdentityServer";
options.ResponseType = OidcConstants.ResponseTypes.CodeIdToken;
options.ClientId = "IdentityClientId";
options.ClientSecret = "IdentityClientSecret";
options.RequireHttpsMetadata = false;
options.SignedOutRedirectUri = websiteSettings.Home;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("ordering-api");
options.Scope.Add("offline_access");
options.SaveTokens = true;
options.RemoteAuthenticationTimeout = TimeSpan.FromMinutes(30);
options.TokenValidationParameters.RoleClaimType = "role";
options.Events = new OpenIdConnectEvents
{
// .. some events
};
});
我想要的是,当我向我的网络应用程序验证用户身份时,他们可以关闭浏览器,当他们重新打开浏览器时,他们仍然可以使用我的网站 - 他们还没有注销。
当我打开浏览器时,我没有看到 IDS cookie。
您必须在控制器方法(POST:登录)中指示您希望持久登录的用户登录位置。
await _signInManager.SignInAsync(<ApplicationUser>, isPersistent: <boolean>);
这里必须传递第二个参数
true
。默认为 false
。
我添加了选项:
services.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.SlidingExpiration = true;
options.ReturnUrlParameter = "requestedUrl";
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
options.Cookie.IsEssential = true;
options.Cookie.MaxAge = TimeSpan.FromDays(AuthOptions.CookiesLifetime);
});
并添加:
await HttpContext.SignInAsync(new IdentityServerUser(user.UserId.ToString())
{
DisplayName = user.Email,
AdditionalClaims = new List<Claim> { new(JwtClaimTypes.Email, user.Email) }
},
new AuthenticationProperties()
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddDays(AuthOptions.CookiesLifetime),
AllowRefresh = true
});