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

发布于 2024-08-07 22:31:03 字数 339 浏览 0 评论 0 原文

我需要设置一个带有表单身份验证的 Asp.Net 应用程序,以便它满足以下条件:

  1. 用户应在 15 分钟不活动后注销
  2. 用户应在 24 小时后注销,无论活动如何

我相信第一个可以像这样完成在 web.config 中:

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

但是您将如何解决第二个要求呢?

I need to setup an Asp.Net application w/ forms authentication so that it meets the following criteria:

  1. User should log out after 15 minutes of inactivity
  2. User should log out after 24 hours, regardless of activity

I believe the first can be accomplished like so in the web.config:

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

But how would you go about resolving the second requirement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

烟雨凡馨 2024-08-14 22:31:03

MSDN 上有一篇详细的文章,解释了表单身份验证的工作原理以及内容是可用的配置选项。
基本上,表单身份验证使用 cookie(除非您明确告诉它不要这样做)。因此,您可以将 Forms 身份验证 cookie 的到期日期设置为 24 小时。但有一个问题。您可能需要滚动自己的会员代码,因为默认情况下,forms 元素的 timeout 属性也用于设置持久 cookie 的生命周期。而你不希望这样。您需要将 Cookie 的过期时间设置为 24 小时。

它的工作方式是,用户登录后,将创建 Forms 身份验证 cookie,然后将其包含在每个请求中,直至其过期。
来自链接的文章:
在对用户进行身份验证时,成员资格提供程序具有与此类似的代码:

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");
}

您可以使用 FormsAuthenticationTicket 类:

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

表单身份验证使用 Encrypt 方法对表单身份验证票证进行加密和签名:

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

创建 cookie:

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

将 cookie 添加到 cookie 集合:

Response.Cookies.Add(authCookie);

这应该是关于它的。

您可能需要滚动自己的 cookie,因为默认情况下,您为 forms 指定的 timeout 属性将用于 cookie 超时。
因此,在您的示例中:

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

cookie 的超时时间也将为 15 分钟。
对于您的情况,更简单的方法可能是使用会话变量来处理强制的 24 小时超时。因为只有当用户在该时间段内实际上处于活动状态时,您才会点击该按钮(否则 cookie 就会超时)。因此,如果会话已处于活动状态超过 24 小时,您可以终止该会话。

There's a detailed article on MSDN that explains how Forms authentication works and what are the available configuration options.
Basically Forms authentication uses cookies (unless you specifically tell it not to). So you could set the expiration date for your Forms authentication cookies to 24 hours. 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. And you don't want that. You'd want to set the expiration for your cookie to 24 hours.

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.
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 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:

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

Create the cookie:

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

Add the cookie to the cookie collection:

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.
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.
Probably the easier approach in your case would be to handle your enforced 24-hour timeout using a session variable. Since you'd only hit that if the user was actually active during that period (otherwise it would have timed-out from the cookie). So you could just terminate a Session if had been active for over 24 hours.

尤怨 2024-08-14 22:31:03

我认为 ASP.Net 中的表单身份验证没有内置任何内容来处理此问题。

您可以创建一个全局应用程序类 (global.asax),处理 Session_Start 事件,并将日期/时间存储在会话变量中,如下所示:

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

然后,您可以处理 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");
        }
    }
}

要处理 OnBeginRequest 事件,您可能需要创建一个自定义 HttpModule - 请参阅此处:
http://msdn.microsoft.com/en-us /library/ms227673(VS.85).aspx

I do not think forms auth in ASP.Net has anything built in to handle this.

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:

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:

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

倥絔 2024-08-14 22:31:03

那么,作为一个简单的解决方案,您可以使用缓存的超时通知功能作为“提醒”/回调,以便在创建会话 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();
}

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.

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文