使用Azure AD OpenIdConnect和自定义中间件的ASP网络核心身份验证中的Cookie过期 [英] Cookie expiry in ASP NET Core Authentication using Azure AD OpenIdConnect and custom middleware

查看:30
本文介绍了使用Azure AD OpenIdConnect和自定义中间件的ASP网络核心身份验证中的Cookie过期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在通过OpenIdConnect身份验证模型使用Azure AD对我的.NET核心应用程序进行身份验证时,我当前正在努力设置Cookie/auth令牌上的超时。

正在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分钟过期的身份验证令牌(和Cookie),并忽略我已尝试的2小时过期设置。

我一直在参考来自GitHub的最新源代码示例,这些示例来自于ASPnet/安全存储库...但是,所有这些都没有提到任何有关覆盖发出的默认过期时间的内容。

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

我找到的大多数示例仍然引用旧的AspNet库,而不是AspNetCore库。

有些文章建议使用SignInAsync并将Persistent设置为True允许遵守ExpireTimeSpan,但是在调用它时会抛出一个"不受支持的异常"。可能不支持通过Azure AD登录Async?

有人对如何实现这一点有什么见解吗?

推荐答案

UseOpenIdConnectAuthentication集合UseTokenLifetime = false

这篇关于使用Azure AD OpenIdConnect和自定义中间件的ASP网络核心身份验证中的Cookie过期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆