asp.net的表单验证

在程序中使用表单验证需要以下步骤:

1. 在web.config文件中配置表单验证。

将web.config文件中的<authentication/>配置节的mode特性设为Forms就可以使用表单验证了:

<authentication mode="Forms">
<forms name="AuthCookieName" loginUrl="login.aspx" timeout="30" slidingExpiration="false" defaultUrl="default.aspx">
</forms>
</authentication>

forms主要选项说明:

name:    cookie的名称,默认值为.ASPXAUTH;

loginUrl:   指定登录页面;

timeout:    过期时间(分钟),默认为30;

defaultUrl:  指定登录后的默认返回页面;

domain:   指定cookie的有效域;

2. 实现代码

首先需要引入命名空间:

using System.Web.Security;
if (IsValidUser(username))
{
FormsAuthentication.RedirectFromLoginPage(username, false);
}

ForumsAuthentication.RedirectFromLoginPage()

这个方法同时执行了以下任务:
1. 为用户创建了一个验证票据;
2. 对验证票据中的信息进行加密;
3. 创建一个Cookie来保存加密的票据信息;
4. 将Cookie添加到HTTP响应,并发送至客户端;
5. 重定向至web.config配置的默认页面

PS:cookie通过一个机器特定的密钥来加密,这个密钥在machine.config中定义。如果在一个WEB集群中,你需要保证所有的服务器使用同样的密钥,这样各服务器才能够互相解密所创建的cookie。

若需要更灵活地设置Cookie的过期时间,可使用FormsAuthentication的GetAuthCookie()方法创建持久化Cookie,设置过期时间,然后自已将Cookie写到HTTP响应中去。

将上面的代码稍做修改即可:

if (IsValidUser(username))
{
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(username, true);
authCookie.Expires = DateTime.Now.AddDays(10);
Response.Cookies.Add(authCookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, true));
}

验证是否成功:  Request.IsAuthenticated

已验证用户名称: HttpContext.Current.User.Identity.Name

删除验证:    FormsAuthentication.SignOut();

FIN




原文地址:https://www.cnblogs.com/elycir/p/2227064.html