Forms身份验证基本原理

来源:互联网 发布:如何ping ip地址端口 编辑:程序博客网 时间:2024/05/29 15:49

我们来看下Forms身份验证基本原理:
一 身份验证
要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设
置:
<authentication mode="Forms">
    <forms name=".ASPXAUTH" loginUrl="login.aspx" timeout="30"
path="/"/>
</authentication>
其中<authentication mode="Forms"> 表示本应用程序采用Forms验证方
式。
<forms>标签中的name表示指定要用于身份验证的Cookie。默认是.ASPXAUTH,其实你可以用任何名字,这也就是你在本地硬盘上看到的cookie里面的前面的几个字.
Forms的验证过程如下:1,生成身份验证票,2,加密身份验证票.3,写回客户端,4,浏览器重新定向.其实这一系列的动作如果我们不用roles的话都是通过FormsAuthentication.RedirectFromLoginPage方法来完成了这一系列的工作任务.但是既然我们要使用roles授权,我们就不能够使用这个方法,而要分开来,一步步完成.
首先是创建身份验证票,首先我们看看FormsAuthenticationTicket类的一个构造函数:
public FormsAuthenticationTicket(
int version, //设为1
string name, //用户标示
DateTime issueDate, //Cookie 的发出时间, 设置为 DateTime.Now
DateTime expiration, //过期时间
bool isPersistent, //是否持久性(根据需要设置,若是设置为持久性,在发出
cookie时,cookie的Expires设置一定要设置)
string userData, //这里用上面准备好的用逗号分割的role字符串
string cookiePath // 设为”/”,这要同发出cookie的路径一致,因为刷新cookie
要用这个路径
);
最后个参数可以省略
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket
(1,”kent”,DateTime.Now, DateTime.Now.AddMinutes(30), false,UserRoles)

然后加密:

string hashTicket = FormsAuthentication.Encrypt(ticket);
//设置验证票cookie,第一个参数为cookie的名字,第二个参数为cookie的值也就是加密后的票
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,hashTicket);
//设置cookie的有效期是一个礼拜
cookie.Expires = DateTime.Now.AddDays(7);
//把cookie加进Response对象发生到客户端
Response.Cookies.Add(cookie);
//得到请求的url
string requestUrl = FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName,false);
//不要使用FormsAuthentication.RedirectFromLoginPage方法,因为这个方法会重写cookie
//重新定向到请求的url
Response.Redirect(requestUrl);

原创粉丝点击