Azure Ad .net core 2.0的会话超时 [英] Session timeout with azure Ad .net core 2.0

查看:79
本文介绍了Azure Ad .net core 2.0的会话超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Azure广告对.net core 2.0应用程序进行身份验证.我通过身份验证成功.但是我需要在空闲时间之后进行会话超时.

I am trying to authenticate .net core 2.0 application with the Azure ad. I got it successful with authentication. But I need to session timeout after idle time.

请找到我的startup.cs配置

Please find my startup.cs config

配置

        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;
         });

推荐答案

作为

服务器使用 IdleTimeout 属性来确定会话在被放弃之前可以空闲多长时间.此属性与Cookie的有效期无关.通过会话中间件(从其中读取或写入)的每个请求都会重置超时.

The server uses the IdleTimeout property to determine how long a session can be idle before its contents are abandoned. This property is independent of the cookie expiration. Each request that passes through the Session middleware (read from or written to) resets the timeout.

我启用了会话状态,然后在一个动作中设置会话值,并在另一个动作中读取它们.根据我的测试,您对 AddSession 的配置将发出一个默认名称为 .AspNetCore.Session 的cookie,并包含浏览器的会话ID.IdleTimeout是1分钟,如果您读取或更新了会话值,则IdleTimeout将被重置.

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. The IdleTimeout is 1 minute and if you read or update the session values, then the IdleTimeout would be reset.

更新:

AFAIK,使用 services.AddSession 时, SessionOptions 下没有SessionEvents.据我了解,您可以在使用Cookie身份验证时设置Cookie过期时间,然后添加处理以删除会话值,并在Cookie无效时将注销请求发送到AAD.这是我的配置,您可以参考以下内容:

AFAIK, there is no SessionEvents under SessionOptions when using services.AddSession. 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. 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;
    });
}

这篇关于Azure Ad .net core 2.0的会话超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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