忽略表单身份验证超时
本文关键字:超时 身份验证 表单 | 更新日期: 2023-09-27 17:57:23
我正在使用 asp.net 表单身份验证来要求用户在访问特定页面时登录。我希望用户在 5 分钟不活动后必须再次登录,但无论我在 web.config 中表单部分的超时值中输入什么,用户只有在会话状态到期后才会被踢出。
我尝试过的测试之一涉及此配置:
<system.web>
<sessionState timeout="1" />
<authentication mode="Forms">
<forms loginUrl="~/authentication" timeout="2" slidingExpiration="true"/>
</authentication>
</system.web>
如果我登录并保持空闲一分钟,如果我刷新页面,系统会要求我再次登录。但是,我的印象是我应该能够继续工作,直到表单身份验证超时到期。我知道在 1 分钟标记处,滑动过期设置续订我的 cookie 为时已晚,但我应该在 cookie 实际过期之前还有一分钟。
如果我删除会话超时部分,则在两分钟后不会要求我登录。需要很长时间(可能 30 分钟)才能要求我重新登录。对我来说,这听起来像是我只在会话状态到期时被要求重新登录。
我在这里错过了什么吗?
下面是所涉及的控制器和方法的基本布局。首先,用户尝试转到招聘人员页面:
public class HireController : Controller
{
[Authorize]
public ActionResult Recruiter()
{
//do stuff after we've been authorized to access this page
}
}
由于用户需要获得授权,因此他们被重定向到身份验证控制器中的登录页面:
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第二个参数设置持久 cookie 如果设置为 true。否则,cookie 不会持久化并在会话超时时丢失。因此,如果您想通过不同的会话(会话超时后)保留身份验证 cookie,请使用以下命令:
FormsAuthentication.SetAuthCookie(userName, true);
但请记住,会话超时后,用户将丢失所有会话变量,这可能会导致 Web 应用中出现错误。
我找到了所有问题的原因。我在global.asax中找到了一堆代码,这些代码操纵用户的会话并基本上覆盖了表单身份验证。此代码在对服务器的每个请求上运行,只要用户仍在会话中进行身份验证,就会保持用户登录状态。这意味着即使表单身份验证cookie过期(它确实过期了!),用户也将保持登录状态。我猜以前的开发人员从表单身份验证开始,然后出于某种原因决定编写自己的东西。我们决定更改会话超时,以便用户在 5 分钟后注销,而不是默认的 20 分钟。
以下是来自global.asax的一些代码,这些代码导致我几乎秃顶:
protected void Application_PreRequestHandlerExecute()
{
HttpSessionState session = HttpContext.Current.Session;
if (session == null)
return;
IUser user = (session[HttpSecurityContext.SECURITY_CONTEXT_KEY] as IUser) ?? CreateUser();
securityContext.SetCurrent(user);
}
protected void Application_PostRequestHandlerExecute()
{
HttpSessionState session = HttpContext.Current.Session;
if (session == null) return;
session[HttpSecurityContext.SECURITY_CONTEXT_KEY] = securityContext.Current;
}
private IUser CreateUser()
{
IUserLocation location = LocateUser();
IUser user = Common.Security.User.CreateAnonymous(location);
SetupUserPreferences(user);
return user;
}
这就是我们在 web.config 中为会话超时所做的更改:
<system.web>
<sessionState timeout="5"/>
</system.web>
我必须将以下内容添加到web.config文件中,以防止未经授权的用户访问该页面:
<authorization>
<deny users="?" />
</authorization>
显然这是非常标准的程序,我很惊讶我在搜索中没有更早地遇到它。这篇 msdn 文章实际上提到了添加该部分。