ASP.NET 中的表单身份验证(Forms Authentication)

来源:互联网 发布:淘宝卖家店铺找不到了 编辑:程序博客网 时间:2024/05/17 01:49

表单验证可以通使用一个登录页面验证用户的用户名和密码。未通过验证的请求会被重定向到登录页面,要求用户输入其凭据信息(同常是用户名和密码)。如果请求通过验证,系统将签发一个身份验证票据,在用户会话期间,这个票据维护用户的身份标识信息以及用户角色。通过FormsAuthentication 类可以访问用户的标识信息和角色。

下面实现一个简单的Forms Authentication:

(1)新建一个新的Web应用程序,创建一个登录页面。

(2)修改应用程序根目录下的web.config文件,设置应用程序的验证模式为表单验证。

<system.web><authentication mode="Forms">    <forms loginUrl="Logon.aspx" name=".ASPXFORMSAUTH">    </forms></authentication></system.web>


(3)在限制访问的目录下创建一个web.config文件,修改authorization配置节阻止匿名用户的访问。
<system.web>
  <authorization>
       <deny users="?"/>
  </authorization>
</system.web>

(4)在登录面页中鉴别用户并且创建一个表单验证票据。

下面的代码假定你有一个IsAuthenticated函数用于验证用户,一个GetRoles函数用于获取用户角色。

void OnLogin(object sender, EventArgs e)
 {
  if(IsAuthenticated(username, password))
  {
   string roles = GetRoles(username);
   FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    1, // 版本
    username, // 用户名
    DateTime.Now, // 票据的签发时间
    DateTime.Now.AddHours(1), // 票据的过期时间
    false, // 是否为永久Cookie
    roles // 附加的用户数据,此处用来存放用户角色
   );

   string encryptedTicket = FormsAuthentication.Encrypt(ticket);
   HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
   Response.Cookies.Add(cookie);
   Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));
  }
 }

(5)捕获验证请求事件,创建一个GenericPrinciple对象。

void Application_AuthenticateRequest(object sender, EventArgs e)
 {
  HttpCookie cookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
  FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
  string[] roles = ticket.UserData.Split(new char[] { ',' });
  FormsIdentity identity = new FormsIdentity(ticket);
  GenericPrincipal priciple = new GenericPrincipal(identity, roles);
  Context.User = priciple;
 }

 
原创粉丝点击