首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >ASP.NET web应用程序-即使isPersistent设置为true,用户在几个小时不活动后也会注销。

ASP.NET web应用程序-即使isPersistent设置为true,用户在几个小时不活动后也会注销。
EN

Stack Overflow用户
提问于 2020-09-18 00:29:35
回答 1查看 136关注 0票数 0

我在Microsoft.Owin web应用程序中使用ASP.NET和Microsoft.AspNet.Identity库进行用户身份验证。从下面的代码中可以看到,IsPersistent属性设置为true,ExpiresUtc设置为5年后。

因此,当用户登录时,只要存在活动,就会创建ApplicationCookie并登录用户。经过几个小时的不活动(我还不知道注销发生的时间限制),应用程序loggs会自动关闭用户,即使身份验证设置为持久性,并且5年后到期。我还尝试将sessionState属性在Web.config中设置为500000,但仍然没有成功。

我想让用户尽可能长时间登录。我遗漏了什么?我必须指出,这种情况只发生在生产中,而在本地执行应用程序时(在我的机器上使用IIS Express ),这种情况还没有发生,但这可能是另一个原因。

以下是身份验证设置代码:

代码语言:javascript
运行
复制
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login"),
      ExpireTimeSpan = TimeSpan.FromDays(1825),
      CookieHttpOnly = true,
      SlidingExpiration = true
});

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

var facebookOptions = new FacebookAuthenticationOptions()
{
      AppId = "...",
      AppSecret = "...",
      BackchannelHttpHandler = new FacebookBackChannelHandler(),
      UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
      Scope = { "email" }
};

var google = new GoogleOAuth2AuthenticationOptions()
{
      ClientId = "...",
      ClientSecret = "...",
      Provider = new GoogleOAuth2AuthenticationProvider()
};
google.Scope.Add("email");

app.UseGoogleAuthentication(google);
app.UseFacebookAuthentication(facebookOptions);

下面是使用外部登录提供程序登录的代码:

代码语言:javascript
运行
复制
private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id.ToString());

    AuthenticationManager.SignIn(
        new AuthenticationProperties {
            IsPersistent = isPersistent,
            AllowRefresh = true,
            ExpiresUtc = DateTime.UtcNow.AddDays(1825)
        }, 
        identity, 
        rememberBrowserIdentity
    );
}


[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    Session["Workaround"] = 0;
    return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}


[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    ApplicationUser user = null;
    try
    {
        user = await UserManager.FindAsync(loginInfo.Login);
    }catch(Exception exception)...

    if (user != null)
    {
        try
        {
            await SignInAsync(user, isPersistent: true);
        }catch (Exception exception)...

        return RedirectToLocal(returnUrl);
    }
    else
    {
        ViewBag.ReturnUrl = returnUrl;
        ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
        return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { ImePrezime = loginInfo.ExternalIdentity.Name, LoginProvider = loginInfo.Login.LoginProvider, ImePrezimeNaPosluzitelju = loginInfo.ExternalIdentity.Name, Mail = loginInfo.Email, UserName = loginInfo.DefaultUserName });
    }
 }


 [HttpPost]
 [AllowAnonymous]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
 {
    if (ModelState.IsValid)
    {
        var info = await AuthenticationManager.GetExternalLoginInfoAsync();
        var user = new ApplicationUser(){...};

        try
        {
            var result = await UserManager.CreateAsync(user);

            if (result.Succeeded)
            {
                var roleresult = UserManager.AddToRole(user.Id, "User");
                try
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        IKorisniciBL IKorisniciBL = BLFactory.KreirajInstancuKorisnika<IKorisniciBL>();

                        IKorisniciBL.DodajKorisnika(user.Id, user.ImePrezimeNaPosluzitelju, user.ImePrezime, user.UlicaKucniBroj, postanskiBroj, user.Mjesto, user.BrojTelefona, user.Email);
                        await SignInAsync(user, isPersistent: true);
                        return RedirectToLocal(model.ReturnUrl);
                    }
                }
                catch (Exception ex)...
            }
        }
        catch(Exception ex)...
    }

    ViewBag.ReturnUrl = model.ReturnUrl;
    return View(model);
}

下面是ChallengeResult类,您还可以看到isPersistent属性设置为true,ExpiresUtc设置为max值。

代码语言:javascript
运行
复制
private class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null)
    {
    }

    public ChallengeResult(string provider, string redirectUri, string userId)
    {
        LoginProvider = provider;
        RedirectUri = redirectUri;
        UserId = userId;
    }

    public string LoginProvider { get; set; }
    public string RedirectUri { get; set; }
    public string UserId { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        var properties = new AuthenticationProperties() { RedirectUri = RedirectUri, IsPersistent = true, ExpiresUtc = DateTime.MaxValue, AllowRefresh = true };
        if (UserId != null)
        {
            properties.Dictionary[XsrfKey] = UserId;
        }
        context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
    }
}
EN

Stack Overflow用户

发布于 2020-09-22 00:47:03

它可以设置为IIS级别上不需要的设置,因为IIS在应用程序上设置cookie设置。

你查过裁判了吗?https://www.stigviewer.com/stig/iis_8.5_site/2018-01-03/finding/V-76777

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63947776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档