在 ASP.NET MVC 项目中使用 Azure AD 身份验证续订会话

时间:2021-07-28 09:15:36

标签: c# .net asp.net-mvc azure-active-directory openid-connect

我已使用 OpenId Connect 在 ASP.NET MVC 项目中配置了 Azure AD 身份验证。身份验证有效,但问题是,60 分钟后会话不再有效。在我的应用程序中,用户闲置一段时间是很常见的,并且应该能够继续工作而无需重新登录。这是我在 Startup.auth.cs 中设置身份验证的方式:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions {
    CookieManager = new SystemWebCookieManager()
});

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = Authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,

        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
           AuthorizationCodeReceived = (context) => 
           {
               return System.Threading.Tasks.Task.FromResult(0);
           }
        }
    });

我已尝试按照 https://www.cloudidentity.com/blog/2016/07/25/controlling-a-web-apps-session-duration-2/ 中的建议添加会话刷新逻辑。这种方法的问题是登录窗口不能显示在框架中。

如何在用户关闭浏览器窗口之前保持会话有效?这似乎是一个应该有一些通用解决方案的常见问题,但我找不到。

1 个答案:

答案 0 :(得分:0)

您可以在类之前的“new OpenIdConnectAuthenticationOptions”部分下的代码中添加以下突出显示的参数:-

app.SetDefaultSignInAsAuthenticationType
(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions {
CookieManager = new SystemWebCookieManager()});

app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
    ClientId = clientId,
    Authority = Authority,
    PostLogoutRedirectUri = postLogoutRedirectUri,

    Notifications = new OpenIdConnectAuthenticationNotifications()
    {
       AuthorizationCodeReceived = (context) => 
       {
           return System.Threading.Tasks.Task.FromResult(0);
       }
    UseTokenLifetime = false
  }
 });'

身份验证会话生命周期(例如 cookie)应与身份验证令牌的生命周期相匹配。问题是您需要延长 AAD 中的令牌生命周期,默认情况下设置为一小时。

另外,请找到以下主题的链接供您参考:-

AzureAD and OpenIdConnect session expiration in ASP.net WebForms

Cookie expiry in ASP NET Core Authentication using Azure AD OpenIdConnect and custom middleware

谢谢,

相关问题