简体   繁体   English

Azure Ad .net core 2.0的会话超时

[英]Session timeout with azure Ad .net core 2.0

I am trying to authenticate .net core 2.0 application with the Azure ad. 我正在尝试使用Azure广告对.net core 2.0应用程序进行身份验证。 I got it successful with authentication. 我通过身份验证成功。 But I need to session timeout after idle time. 但是我需要在空闲时间之后进行会话超时。

Please find my startup.cs config 请找到我的startup.cs配置

Configure 配置

        logger.AddConsole(Configuration.GetSection("Logging"));
        logger.AddDebug((category, logLevel) => (logLevel >= LogLevel.Trace));
        app.UseResponseCaching();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
        app.UseSession();
        app.UseAuthentication();

ConfigureServices 配置服务

  services.AddAuthentication(options =>
             {
                 options.DefaultScheme= CookieAuthenticationDefaults.AuthenticationScheme;
                 options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
             })
             .AddOpenIdConnect(options =>
             {
                 options.ClientId = Configuration["Authentication:AzureAd:ClientId"];
                 options.Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
                 options.ClientSecret = Configuration["Authentication:ClientSecret"];
                 options.CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"];
                 options.ResponseType = OpenIdConnectResponseType.IdToken;
             })
             .AddCookie();

             services.AddSession(options =>
         {
             options.IdleTimeout = TimeSpan.FromMinutes(1);
             options.CookieHttpOnly = true;
         });

As the section Implementation Details under Working with Session State states as follows: 正如使用会话状态下的实现详细信息部分所述状态如下:

The server uses the IdleTimeout property to determine how long a session can be idle before its contents are abandoned. 服务器使用IdleTimeout属性确定在放弃会话内容之前可以将会话空闲多长时间。 This property is independent of the cookie expiration. 此属性独立于cookie到期。 Each request that passes through the Session middleware (read from or written to) resets the timeout. 通过会话中间件的每个请求(读取或写入)都将重置超时。

I enabled the session state, then set session values in an action and read them in another action. 我启用了会话状态,然后在一个操作中设置会话值,并在另一个操作中读取它们。 Per my test, your configuration for AddSession would issue a cookie with the default name .AspNetCore.Session and contains the session ID to the browser. 按我的测试,您的配置AddSession会发出带默认名字的cookie .AspNetCore.Session和包含会话ID的浏览器。 The IdleTimeout is 1 minute and if you read or update the session values, then the IdleTimeout would be reset. IdleTimeout为1分钟,如果您读取或更新了会话值,则IdleTimeout将被重置。

UPDATE: 更新:

AFAIK, there is no SessionEvents under SessionOptions when using services.AddSession . AFAIK,使用services.AddSession时, SessionOptions下没有SessionEvents。 Per my understanding, you could set the Cookie expire time when using cookie auth, then add the processing to remove the session values and send the sign-out request to AAD when the cookie is invalid. 据我了解,您可以在使用Cookie身份验证时设置Cookie过期时间,然后添加处理以删除会话值,并在Cookie无效时将注销请求发送到AAD。 Here is my configuration, you could refer to it as follows: 这是我的配置,您可以参考以下内容:

public void ConfigureServices(IServiceCollection services)
{
    // Add MVC services to the services container.
    services.AddMvc();

    // Add Authentication services.
    services.AddAuthentication(sharedOptions =>
    {
        sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        sharedOptions.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })

        // Configure the OWIN pipeline to use OpenID Connect auth.
        .AddOpenIdConnect(option =>
        {
            option.ClientId = Configuration["AzureAD:ClientId"];
            option.Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAd:Tenant"]);
            option.SignedOutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"];
            option.Events = new OpenIdConnectEvents
            {
                OnRemoteFailure = OnAuthenticationFailed,
            };
        })// Configure the OWIN pipeline to use cookie auth.
        .AddCookie(op => {
            op.ExpireTimeSpan = TimeSpan.FromMinutes(20);
            op.LoginPath = "/Account/Login";
            op.Events.OnRedirectToLogin =async(context) =>
                {   
                    //Clean the session values
                    context.HttpContext.Session.Clear();
                    //Sign-out to AAD
                    await context.HttpContext.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
                    //Redirect to op.LoginPath ("/Account/Login") for logging again
                    context.Response.Redirect(context.RedirectUri);
                };
        });

    services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromMinutes(20);
        options.CookieHttpOnly = true;
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM