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

标签 c# azure authentication openid-connect asp.net-core-1.0

在通过 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/

相关文章:

c# - 为什么匿名类型不像 ExpandoObject 那样是动态的?

c# - Excel.Range.Find 使用长度超过 255 个字符的字符串

c# - 如何为生成一系列匿名类型的 linq 查询声明全局变量

azure - 在 azure 函数中绑定(bind)字符串输出队列时出错

c# - 如何将 Windows 身份验证凭据从客户端传递到 Web API 服务

c# - 为什么 ASP.NET Core 3.1 应用程序中的 appsettings 中的 Appinsight 日志级别被忽略?

asp.net - 使用 windows azure 开发时的差异

powershell - 使用 Powershell 为流分析创建 Blob 存储输出时出错

azure - AzCopy 身份验证

javascript - 授权时无法提取授权码