gpt4 book ai didi

c# - 表单例份验证超时被忽略

转载 作者:行者123 更新时间:2023-11-30 20:35:04 25 4
gpt4 key购买 nike

我正在使用 asp.net Forms Authentication 来要求用户在访问特定页面时登录。我希望用户在 5 分钟不活动后必须重新登录,但无论我在 web.config 中的表单部分的超时值中输入什么,用户只会在 session 状态过期后被踢出。

我尝试过的测试之一涉及此配置:

<system.web>   
<sessionState timeout="1" />
<authentication mode="Forms">
<forms loginUrl="~/authentication" timeout="2" slidingExpiration="true"/>
</authentication>
</system.web>

如果我登录并保持空闲一分钟,如果我刷新页面,系统会要求我重新登录。但是,我的印象是我应该能够继续工作,直到表单例份验证超时到期。我知道在 1 分钟标记处,slidingExpiration 设置更新我的 cookie 为时已晚,但在 cookie 实际过期之前我应该​​还有一分钟。

如果我删除 Sessiontate 超时部分,我将不会在两分钟后被要求登录。在我被要求重新登录之前需要很长时间(大概 30 分钟)。这对我来说听起来像是只在 sessionState 过期时才要求我重新登录。

我是不是漏掉了什么?

下面是 Controller 和相关方法的基本布局。首先,用户尝试转到 Recruiter 页面:

public class HireController : Controller
{
[Authorize]
public ActionResult Recruiter()
{
//do stuff after we've been authorized to access this page
}
}

因为用户需要被授权,所以他们被重定向到身份验证 Controller 中的登录页面:

public class AuthenticationController : BaseAuthenticationController
{
private readonly IAuthenticationService AuthenticationService;
public AuthenticationController(IAuthenticationService authService)
: base(authService)
{
AuthenticationService = authService;
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string returnUrl)
{
var special= false;
return View("~/Views/Login/Login.cshtml", new LoginModel(special) { ReturnUrl = returnUrl });
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(LoginCredentials credentials, string returnUrl)
{
try
{
if (!ModelState.IsValid)
{
throw new ApplicationException(GeneralError);
}

base.DoLogin(credentials.Username, credentials.Password);
}
catch (Exception ex)
{
string message = (ex is ApplicationException) ? ex.Message : GeneralError;
ModelState.AddModelError("", message);
return View("~/Views/Login/Login.cshtml", new LoginModel { Username = credentials.Username, ReturnUrl = returnUrl });
}
return RedirectToLocal(returnUrl);

}

private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
if (User.Identity != null && User.Identity.IsAuthenticated)
{
return RedirectToAction("Recruiter", "Hire");
}
return RedirectToAction("Recruiter", "Hire");
}
}

这是 BaseAuthenticationController 类:

  public class BaseAuthenticationController : Controller
{
private readonly IAuthenticationService AuthenticationService;
protected const string GeneralError = "Login failure please try again";

public BaseAuthenticationController(IAuthenticationService authService)
{
AuthenticationService = authService;
}

public void DoLogin(string username, string password)
{
AuthenticationService.Login(username, password);
}
}

这是具体的 IAuthenticationService 类:

 public class WebAuthenticationService : IAuthenticationService
{
private const string InvalidError = "Invalid User Credentials Please try again";
private const string LockoutError = "You have been locked out of the Hiring Center. You will receive an email shortly once your password has been reset.";
readonly string uri = ConfigurationManager.AppSettings["HiringLoginApiBaseUrl"];
private readonly ISecurityContext SecurityContext;

public WebAuthenticationService(ISecurityContext securityContext)
{
SecurityContext = securityContext;
}

private LoginResult GetUserLogin(string username, string password)
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri(uri);
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password)
});
var postResult = httpClient.PostAsync("/api/Login/Post", content).Result;
var loginResult = postResult.Content.ReadAsAsync<LoginResult>().Result;

return loginResult;
}
}

public MembershipProvider AuthenticationProvider
{
get { return Membership.Provider; }
}

public void Login(string userName, string password)
{
var loginResult = this.GetUserLogin(userName, password);
if (!loginResult.IsValid)
{
throw new ApplicationException(InvalidError);
}

if (loginResult.IsLockedOut)
{
throw new ApplicationException(LockoutError);
}

// Maintain the location
IUser current = SecurityContext.Current;

SecurityContext.SetCurrent(User.CreateAuthorized(userName, current.Location, current.Preferences));
FormsAuthentication.SetAuthCookie(userName, false);

}
}

我不太清楚以下行在 WebAuthenticationService 类中的意义:

SecurityContext.SetCurrent(User.CreateAuthorized(userName, current.Location, current.Preferences));

SetCurrent() 方法定义如下:

 public class HttpSecurityContext : ISecurityContext
{
public static string SECURITY_CONTEXT_KEY = "SECURITY_CONTEXT";

public IUser Current
{
get
{
IUser user = HttpContext.Current.User as IUser;
if (user == null)
{
throw new ApplicationException("Context user is invalid;");
}
return user;
}
}

public void SetCurrent(IUser user)
{
HttpContext.Current.User = user;
}
}

Web.Config 成员提供者:

      <membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=asdfasf" connectionStringName="mydb" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="3" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/" />
</providers>
</membership>

最佳答案

您只是为 FormsAuthentication.SetAuthCookie 方法使用了错误的参数值。根据文档 https://msdn.microsoft.com/pl-pl/library/twk5762b(v=vs.110).aspx如果设置为 true,则第二个参数设置持久性 cookie。否则 cookie 不会持久保存并在 session 超时时丢失。因此,如果您想通过不同的 session ( session 超时后)保留身份验证 cookie,请使用:

FormsAuthentication.SetAuthCookie(userName, true);

但是请记住,在 session 超时后,用户将丢失他的所有 session 变量,这可能会导致您的网络应用程序出错。

关于c# - 表单例份验证超时被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38404429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com