简体   繁体   English

ASP.Net-针对特定安全问题的表单身份验证设置

[英]ASP.Net - Forms Authentication setup for specific Security concerns

I need to setup an Asp.Net application w/ forms authentication so that it meets the following criteria: 我需要使用表格身份验证来设置一个Asp.Net应用程序,使其符合以下条件:

  1. User should log out after 15 minutes of inactivity 闲置15分钟后,用户应注销
  2. User should log out after 24 hours, regardless of activity 无论活动如何,用户都应在24小时后注销

I believe the first can be accomplished like so in the web.config: 我相信第一个可以像在web.config中那样完成:

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" timeout="15" slidingExpiration="true"/>
</authentication>

But how would you go about resolving the second requirement? 但是,您将如何解决第二个要求?

I do not think forms auth in ASP.Net has anything built in to handle this. 我认为ASP.Net中的表单身份验证没有内置任何内容可以处理此问题。

You could create a global application class (global.asax), handle the Session_Start event, and store the date/time in a session variable, like so: 您可以创建一个全局应用程序类(global.asax),处理Session_Start事件,并将日期/时间存储在会话变量中,如下所示:

public void Session_Start(object s, EventArgs e)
{
    Session["LoginDate"] = DateTime.Now;
}

Then, you can handle the OnBeginRequest event to check the difference between the session variable and the current date/time: 然后,您可以处理OnBeginRequest事件,以检查会话变量和当前日期/时间之间的差异:

public void Application_OnBeginRequest(object s, EventArgs e)
{
    if (Session["LoginDate"] != null)
    {
        var loginDate = (DateTime)Session["LoginDate"];
        if ((DateTime.Now - loginDate).TotalHours >= 24)
        {
            Session.Abandon();
            Response.Redirect("~/Login.aspx");
        }
    }
}

To handle the OnBeginRequest event, you may need to create a custom HttpModule - see here: http://msdn.microsoft.com/en-us/library/ms227673(VS.85).aspx 要处理OnBeginRequest事件,您可能需要创建一个自定义HttpModule-请参见此处: http : //msdn.microsoft.com/zh-cn/library/ms227673( VS.85) .aspx

There's a detailed article on MSDN that explains how Forms authentication works and what are the available configuration options. MSDN上有一篇详细的文章 ,解释了Forms身份验证的工作原理以及可用的配置选项。 Basically Forms authentication uses cookies (unless you specifically tell it not to). 基本上,表单身份验证使用Cookie(除非您明确告知不要这样做)。 So you could set the expiration date for your Forms authentication cookies to 24 hours. 因此,您可以将Forms身份验证Cookie的到期日期设置为24小时。 But there's a catch. 但是有一个陷阱。 You probably need to roll your own Membership code, since by default, the timeout attribute of the forms element is also used to set the lifetime of the persistent cookie. 您可能需要滚动自己的成员资格代码,因为默认情况下, forms元素的timeout属性还用于设置持久性cookie的生存期。 And you don't want that. 而且你不想要那样。 You'd want to set the expiration for your cookie to 24 hours. 您希望将Cookie的有效期设置为24小时。

The way it works is that after the user logs in, the Forms authentication cookie is created, and afterwards it's included along with each request until it expires. 它的工作方式是,在用户登录后,将创建Forms身份验证cookie,然后将其与每个请求一起包括在内,直到过期为止。 From the linked article: The Membership Provider has code similar to this when authenticating a user: 从链接的文章中:成员资格提供者在验证用户身份时具有类似于以下代码:

if (Membership.ValidateUser(userName.Text, password.Text))
{
    if (Request.QueryString["ReturnUrl"] != null)
    {
        FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
    }
    else
    {
        FormsAuthentication.SetAuthCookie(userName.Text, false);
    }
}
else
{
    Response.Write("Invalid UserID and Password");
}

You can create a Forms Authentication ticket using the FormsAuthenticationTicket class: 您可以使用FormsAuthenticationTicket类创建一个Forms Authentication票证:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
        "cookieName",
        DateTime.Now,
        DateTime.Now.AddHours(24), // value of time out property
        false,
        String.Empty,
        FormsAuthentication.FormsCookiePath);

Forms authentication uses the Encrypt method for encrypting and signing the forms authentication ticket: 表单身份验证使用Encrypt方法对表单身份验证票证进行加密和签名:

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

Create the cookie: 创建cookie:

HttpCookie authCookie = new HttpCookie(
                            FormsAuthentication.FormsCookieName, 
                            encryptedTicket);

Add the cookie to the cookie collection: 将cookie添加到cookie集合中:

Response.Cookies.Add(authCookie);

And that should be about it. 那应该是关于它的。

You probably need to roll your own cookie, because by default, the timeout property that you specified for your forms is the one that's going to be used for the cookie timeout. 您可能需要滚动自己的cookie,因为默认情况下,您为forms指定的timeout属性是将用于cookie超时的属性。 So in your example: 因此,在您的示例中:

<authentication mode="Forms">
  <forms loginUrl="Login.aspx" timeout="15" slidingExpiration="true"/>
</authentication>

The cookie's timeout will be 15 minutes also. Cookie的超时时间也将是15分钟。 Probably the easier approach in your case would be to handle your enforced 24-hour timeout using a session variable. 在您的情况下,可能更简单的方法是使用会话变量处理您强制执行的24小时超时。 Since you'd only hit that if the user was actually active during that period (otherwise it would have timed-out from the cookie). 因为您仅在该时段内用户实际上处于活动状态(否则它将从Cookie超时)中击中该值。 So you could just terminate a Session if had been active for over 24 hours. 因此,如果活动超过24小时,您可以终止会话。

Well, as a simple solution you could use the Cache's timeout notification feature as a "reminder"/callback to abandon the session 24 hours after creating it. 好吧,作为一种简单的解决方案,您可以将缓存的超时通知功能用作“提醒” /回调,以在创建会话后24小时放弃会话。

void Session_Start(object sender, EventArgs e)
{
  Cache.Add(Session.SessionID,Session,null,DateTime.Now.AddHours(24),
  TimeSpan.Zero, CacheItemPriority.High, OnExpireSession)
}

public void OnExpireSession(String k, Object v, CacheItemRemovedReason r)
{
    //uhm.. maybe do some checks if the session was already abandoned?
   ((SessionState)v).Abandon();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM