UseCookieAuthentication 中的 ASP.NET Core Web 应用程序 ExpireTimeSpan 不起作用

标签 asp.net asp.net-core

我使用带有以下选项的 Google Cookie 身份验证:

       app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "MyCookieMiddlewareInstance",
            LoginPath = new PathString("/Account/Login/"),
            AccessDeniedPath = new PathString("/Account/Forbidden/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            ExpireTimeSpan = TimeSpan.FromDays(14.0)
        });

        app.UseGoogleAuthentication(new GoogleOptions()
        {
            SignInScheme = "MyCookieMiddlewareInstance",
            AutomaticAuthenticate = true,
            ClientId = "xxx",
            ClientSecret = "xxx"
        }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public IActionResult ExternalLogin(string provider, string returnUrl = null)
    {
        // Request a redirect to the external login provider.
        var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
        var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
        return Challenge(properties, provider);
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult ExternalLoginCallback(string returnUrl = null, string remoteError = null)
    {
        return RedirectToLocal(returnUrl);
    }

通过 Google 授权后,cookie 将在 30 分钟后过期。它们是为 session 创建的。

enter image description here

我应该怎样做才能延长探索时间?

最佳答案

在使用 ASP.NET Core Identity 时,不应使用自己的 cookie 中间件,因为 app.UseIdentity() 已经为您完成了该操作。调用 services.AddIdentity(options => { ...}) 时,您可以直接在身份选项中配置 cookie 生命周期/名称/路径。

如果您不使用 isPersistent: true 调用 _signInManager.ExternalLoginSignInAsync,您将获得一个 session Cookie,该 Cookie 在关闭浏览器时会过期。您可以更新 ExternalLoginCallback 来解决此问题:

[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    if (remoteError != null)
    {
        ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
        return View(nameof(Login));
    }
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        return RedirectToAction(nameof(Login));
    }

    // Sign in the user with this external login provider if the user already has a login.
    // Specify isPersistent: true to avoid getting a session cookie.
    var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: true);
    if (result.Succeeded)
    {
        // Update any authentication tokens if login succeeded
        await _signInManager.UpdateExternalAuthenticationTokensAsync(info);

        _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
        return RedirectToLocal(returnUrl);
    }
    if (result.RequiresTwoFactor)
    {
        return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
    }
    if (result.IsLockedOut)
    {
        return View("Lockout");
    }
    else
    {
        // If the user does not have an account, then ask the user to create an account.
        ViewData["ReturnUrl"] = returnUrl;
        ViewData["LoginProvider"] = info.LoginProvider;
        var email = info.Principal.FindFirstValue(ClaimTypes.Email);
        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
    }
}

关于UseCookieAuthentication 中的 ASP.NET Core Web 应用程序 ExpireTimeSpan 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707783/

相关文章:

c# - 使用 String.ToUpperInvariant() 规范化字符串

c# - 在代码隐藏中从 Repeater 获取值

带有 MVC6 的 angular2,浏览器无法访问 node_modules 内的脚本

asp.net-core - 使用 ASP.NET Core 库禁用 Application Insights 采样

c# - ASP.Net 控件的 InnerHTML 和 InnerText 属性之间的区别?

c# - EF 6 不选择最近更新的值,除非我重建项目

c# - 根据子集合总结一个属性

visual-studio-2015 - .NET Core Web App 不会因异常而中断,并且异常中没有详细信息

c# - 如何从 Razor Pages 应用程序中的插件动态加载页面?

asp.net-core - ASP.NET 核心 : JavaScript files getting cached