表单身份验证超时被忽略

时间:2016-07-15 20:16:07

标签: c# asp.net asp.net-mvc-4 cookies forms-authentication

我正在使用asp.net Forms Authentication要求用户在访问特定页面时登录。我希望用户在不活动5分钟后再次登录,但无论我在web.config中的表单部分的Timeout值中放入什么,用户只有在会话状态到期后才会启动。

我尝试过的其中一项测试涉及这种配置:

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

如果我登录并保持闲置一分钟,我会被要求在刷新页面时再次登录。但是,我的印象是我应该能够继续工作,直到表单身份验证超时到期。据我所知,在1分钟标记处,slideExpiration设置更新我的Cookie为时已晚,但我还应该在Cookie实际到期之前再过一分钟。

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

我在这里错过了什么吗?

这是所涉及的控制器和方法的基本布局。首先,用户尝试转到招聘人员页面:

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>

3 个答案:

答案 0 :(得分:2)

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

FormsAuthentication.SetAuthCookie(userName, true);

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

答案 1 :(得分:2)

我找到了所有问题的原因。我在global.asax中发现了一堆代码来操纵用户的会话,并基本上覆盖了表单身​​份验证。此代码在对服务器的每个请求上运行,并且只要它们仍在会话中进行身份验证,就会使用户保持登录状态。这意味着即使表单auth cookie已过期(它确实!),用户仍将保持登录状态。我猜测以前的开发人员使用表单auth开始,然后出于某种原因决定编写自己的东西。我们决定更改会话超时,以便用户在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>

答案 2 :(得分:0)

我必须将以下内容添加到web.config文件中,以防止未经授权的用户访问该页面:

<authorization>
    <deny users="?" />
</authorization>

显然这是非常标准的程序,我很惊讶我在搜索的早期没有遇到它。 This msdn文章实际上提到添加​​该部分。

相关问题