【问题标题】:Implement Auto Redirect on Session Idle timeout using Azure AD and OAuth2.0使用 Azure AD 和 OAuth2.0 实现会话空闲超时自动重定向
【发布时间】:2022-01-25 02:59:49
【问题描述】:

我们的应用程序正在使用 SSO(单点登录)功能进行用户身份验证,该功能正在检查来自 Azure Active Directory 的用户身份。

我们在Startup.cs类的Configure Services()方法中配置了一个SSO,这里我们使用AddCookie(),并将过期时间设置为29分钟。

根据我的理解,使用Ouath2.0 的 SSO 实现会在设置的 cookie 过期空闲时间段结束后自动重定向用户。 我在这里可能错了,因为它没有按预期工作,即使经过数小时的空闲时间,会话也不会过期。

任何人都可以检查下面的代码实现并提出更改以实现所需的功能吗?

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    //configure my sso
    MySsoProvider.ConfigureSso(services, Configuration);

    services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
    //initialize azure provider
    services.AddTransient(CreateAzureBlobFileProvider);
    //ad app insight telemetry
    services.AddApplicationInsightsTelemetry();
}
        
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    app.Use((context, next) =>
    {
        context.Request.Scheme = "https";
        return next();
    });
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
    AzureStorageAccount.Load(Configuration);
}

MySsoProvider.cs:

public static void ConfigureSso(IServiceCollection services, IConfiguration Configuration)
{
    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "PingCookie";
        options.DefaultSignInScheme = "PingCookie";
        options.DefaultChallengeScheme = "Ping";
    }).AddCookie("PingCookie", options =>
    {
        options.Cookie.MaxAge = new TimeSpan(0, 29, 0);
        options.ExpireTimeSpan = new TimeSpan(0, 29, 0); //cookie exipration set to 29 minutes
    }).AddOAuth("Ping", options =>
    {
        options.ClientId = Configuration["abc-def-sso-clientid"];
        options.ClientSecret = Configuration["abc-def-sso-secret"];

        options.CallbackPath = new PathString("/signin-ping");

        options.Scope.Add("openid profile email");
        options.UsePkce = true;
        options.SaveTokens = true;

        options.AuthorizationEndpoint = Configuration["Ping:AuthorizationEndpoint"];
        options.TokenEndpoint = Configuration["Ping:TokenEndpoint"];
        options.UserInformationEndpoint = Configuration["Ping:UserInformationEndpoint"];

        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "immutable_id");
        options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
        options.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
        options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
        options.ClaimActions.MapJsonKey("urn:openid:groups", "groups");

        options.Events = new OAuthEvents
        {
            OnCreatingTicket = async context =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                response.EnsureSuccessStatusCode();

                var responseText = await response.Content.ReadAsStringAsync();

                var user = JsonDocument.Parse(responseText);
                context.RunClaimActions(user.RootElement);
            }
        };
    });
}

所需功能:

  • 我们正在寻找用户在以下情况下自动重定向到其他页面 应用程序空闲 30 分钟(用户不执行任何操作)

【问题讨论】:

    标签: c# asp.net-core oauth-2.0 azure-active-directory session-cookies


    【解决方案1】:

    请检查您是否可以尝试通过设置 UseTokenLifetime 、Sliding expiration 等对配置进行小的更改,如下所示:

    根据Configure ASP.NET Core Identity | Microsoft Docs ,ConfigureApplicationCookie必须在调用AddIdentity或AddDefaultIdentity后调用。

    代替 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 的 CookieAuthenticationDefaults.AuthenticationScheme,如果您有 'Cookies' 身份验证方案,请使用如下:

        services.AddAuthentication(options =>
        {
        options.DefaultAuthenticateScheme = "Cookies";
        options.DefaultSignInScheme = " Cookies ";
        options.DefaultChallengeScheme = "Ping";
        }).AddCookie("Cookies", options =>
        {
        options.UseTokenLifetime = false;
        options.LoginPath = "/Auth/Login";
        options.LogoutPath = "/Auth/Logout";
        options.Cookie.MaxAge = TimeSpan. FromMinutes(29);
        (or) //options.Cookie.Expiration = TimeSpan.FromMinutes(29);
        
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromMinutes(29);
        
        });

    如果 SlidingExpiration 设置为 true,那么 cookie 将在 ExpireTimeSpan 中途的任何请求中重新发出

    (要么寻找持久性 cookie,要么增加会话超时时间。)

    在登录页面将IsPersistent设置为true:

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties
    {
    IsPersistent = true,
    RedirectUri = "/Auth/Login",
    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(29)
    });
    

    将其设置为 false 以使 cookie 的行为类似于 Session

    参考资料:

    1. Cookie authentication in aspnet core3.0 no working (microsoft.com)
    2. ASP.NET Core 3.1 application with Identity logging off quickly - Stack Overflow

    【讨论】:

      猜你喜欢
      • 2010-11-03
      • 2021-03-07
      • 2022-10-04
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 2013-06-18
      • 2017-09-09
      • 2012-02-17
      相关资源
      最近更新 更多