在通过 OpenIdConnect 身份验证模型使用 Azure AD 验证我的 .NET Core 应用程序时,我目前正在努力设置 cookie/auth token 的超时。
登录方案通过以下方式在ConfigureServices 方法中设置:
services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
然后我将按如下方式设置我的配置:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
CookieName = "MyCookie",
ExpireTimeSpan = TimeSpan.FromHours(2)
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions()
{
Authority = authorityUri.AbsoluteUri,
ClientId = azureOptions.ClientId,
ClientSecret = azureOptions.ClientSecret,
ResponseType = OpenIdConnectResponseTypes.CodeIdToken,
Events = new OpenIdConnectEvents()
{
OnAuthorizationCodeReceived = async context =>
{
await aAuthenticateMiddleware.OnAuthenticate(context, logger);
}
}
});
app.UseMiddleware<aAuthenticateMiddleware>();
请注意,我没有使用内置的身份(因为它对我们的目的来说不实用),而是使用自定义中间件。
在中间件层中,我检查用户是否经过身份验证,如果没有则发出质询:
var authenticationProperties = new AuthenticationProperties() { RedirectUri = context.Request.Path.Value ?? "/" };
authenticationProperties.AllowRefresh = false;
authenticationProperties.IssuedUtc = DateTime.Now;
authenticationProperties.ExpiresUtc = DateTime.Now.AddHours(2);
await context.Authentication.ChallengeAsync(
authenticationManager.IdentityProvider.AuthenticationScheme,
authenticationProperties,
ChallengeBehavior.Automatic
);
这一切都工作正常,并正确验证用户身份等,但是这是发出 15 分钟到期时间的身份验证 token (和 cookie),并忽略我尝试设置的 2 小时到期时间。
我一直在引用来自 aspnet/security 存储库的 GitHub 的最新源代码示例......但是这些都没有提及有关覆盖默认过期日期的任何内容。
https://github.com/aspnet/Security/tree/dev/samples/OpenIdConnect.AzureAdSample
我发现的大多数示例仍然引用旧的 AspNet 库而不是 AspNetCore 库。
一些文章建议使用 SignInAsync 并将持久性设置为 True 允许遵守 ExpireTimeSpan,但是这会在调用它时引发“不支持的异常”。也许 Azure AD 不支持 SignInAsync?
有人知道如何实现这一目标吗?
最佳答案
在UseOpenIdConnectAuthentication
中设置UseTokenLifetime = false
关于c# - 使用 Azure AD OpenIdConnect 和自定义中间件的 ASP NET Core 身份验证中的 Cookie 过期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37533856/