使用 Azure AD OpenIdConnect 和自定义中间件的 ASP NET Core 身份验证中的 Cookie 过期

Jam*_*son 5 c# authentication azure openid-connect asp.net-core-1.0

目前,在通过 OpenIdConnect 身份验证模型使用 Azure AD 验证我的 .NET Core 应用程序时,我正在努力设置 cookie/auth 令牌的超时。

登录方案通过以下方式在ConfigureServices 方法中设置:

    services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);
Run Code Online (Sandbox Code Playgroud)

然后我设置我的配置如下:

    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>();
Run Code Online (Sandbox Code Playgroud)

请注意,我没有使用内置的身份(因为它对我们的目的来说不实用),而是使用自定义中间件。

在中间件层中,我检查用户是否经过身份验证,如果没有发出质询:

    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
    );
Run Code Online (Sandbox Code Playgroud)

这一切都工作正常,并正确验证用户身份等,但是这是发出 15 分钟到期日的身份验证令牌(和 cookie),并忽略我尝试设置的 2 小时到期日。

我一直在参考来自 aspnet/security 存储库的 GitHub 的最新源示例......但是这些都没有提到有关覆盖默认过期日期的内容。

https://github.com/aspnet/Security/tree/dev/samples/OpenIdConnect.AzureAdSample

我发现的大多数示例仍然引用旧的 AspNet 库而不是 AspNetCore 库。

一些文章建议使用 SignInAsync 并将持久性设置为 True 允许遵守 ExpireTimeSpan,但是这会在调用它时引发“不支持的异常”。也许 Azure AD 不支持 SignInAsync?

有谁对如何实现这一目标有任何见解?

Gar*_*y W 1

在UseOpenIdConnectAuthentication集合中UseTokenLifetime = false