asp.net forms验证下

我们首先假设一个场景:用户现在已经打开了我们的首页Default.aspx,但是有些资源只能是登录用户才可以看到的,那么如果这个用户想要查看这些资源,那么他就要登录。而且这个用户已经有了一个帐号。(我们本篇主要的话题是身份验证,至于创建用户账户是怎么创建的,我们不关心,方法很多,如直接一个数据库插入就行了!)
  我们现在就把我们的一些流程说下:

  1.用户登录,在输入框中输入用户名和密码信息

  2.点击登录按钮后,到数据库中查询该用户是否存在

  3 如果存在,服务器端代码就创建一个身份验证的票据,保存在cookie中,然后发送到客户端的浏览器

  4.用户已经有了验证的cookie,那么就页面就跳转到用户之前请求的页面

  数据库准备

  那么下面我们就开始详细讲述:

  首先,我们我们肯定要先得创建一个数据库,我们就取名为Login表,创建一个用户信息表,我们在在表中建立三个字段UserName,UserPassword,UserRole(大家可以创建更多字段,我这里只是演示,大家可以扩展的). 至于表中的数据,大家自己随便插入几条!

  代码编写

  因为我们常常要验证用户,所以我们把验证用户的代码写成一个方法放在App_Code目录下的Helpers.cs类中

  代码如下:

  验证代码

 

 public static bool ValidateUser(string username, string password)
  {
  SqlConnection con = new SqlConnection();
  con.ConnectionString =
  ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString;
  SqlCommand com = new SqlCommand();
  com.Connection = con;
  com.CommandText = “Select Count(*) From Users Where Username=@Username and UserPassword=@Password”;
  com.Parameters.AddWithValue(“@Username”, username);
  com.Parameters.AddWithValue(“@Password”, password);
  con.Open();
  int cnt = (int)com.ExecuteScalar();
  con.Close();
  return (cnt > 0);
  }


  然后我们就创建一个登录的页面Login.aspx,在页面上面放入两个TextBox,分别用来供用户输入用户名和密码。

  放上一个按钮,用来登录。

  回到Helpers.cs中,我再添加一个方法,来获取用户的角色:

  Code

  public static string GetRoleForUser(string username )
  {
  //创建链接
  SqlConnection con = new SqlConnection();
  con.ConnectionString =
  ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString;
  SqlCommand com = new SqlCommand();
  com.Connection = con;
  //执行命令
  com.CommandText = “Select UseRole m Users Where Username=@Username;
  com.Parameters.AddWithValue(“@Username”, username);
  con.Open();
  //返回结果
  string userRole= (string)com.ExecuteScalar();
  con.Close();
  }


  为了启动Forms验证,我们还得到web.config文件中配置,如下:


 <authentication mode=”Forms”>
    =”.mycookie” path=”/” loginUrl=”Login.aspx” protection=”All”
timeout=”40” />
authentication>


  并且不允许匿名用户访问我们的网站 :


<authorization>
<deny users=”?”/>
>


  然后我们就开始在Login.aspx的登录按钮下面写代码了:

  基本思想如下:

  1.验证用户是否存在,

  2.如果存在,同时获取用户的角色

  3.创建身份验证票据和cookie,并且发送到客户端的浏览器中
代码都加了注释,通过之前的基础,相信大家可以对下面的代码没有问题。

Code
  Code
  protected void LoginCallback(object sender, EventArgs e)
  {
  if (Helpers.ValidateUser(UserName.Text, Password.Text))
  {
  //获取用户的角色
  string rolenames = Helpers.GetRolesForUser(UserName.Text);
  //创建身份验证票据
  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
  UserName.Text, DateTime.Now, DateTime.Now.AddSeconds(40), false, roles);
  //加密票据
  string encryptedTicket = FormsAuthentication.Encrypt(ticket);
  //创建新的cookie
  HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
  //把加密后的票据信息放入cookie
  cookie.Value = encryptedTicket;
  //把cookie添加到响应流中
  Response.Cookies.Add(cookie);
  //把cookie发送到客户端
  Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text,false),true);
  }
  }


  好了,现在如果我们正确的输入用户名和密码,那么我们的浏览器中就有了身份验证的cookie了,现在我们的页面就要马上从原来的Login.aspx转向到Default.aspx页面了,我们现在把这个转向的过程在头脑中把它慢速化,因为我们要分析这个过程。

  在Login.aspx转向到Default.aspx页面跳转的过程中,其实我们在请求Default.aspx页面,这个我们之前请求的过程没有任何的区别,也是一样要经历ASP.NET的一些生命周期,但是这次我们的浏览器中已经有了身份验证的cookie,ASP.NET运行时在处理,在处理Application_AuthenticateRequest事件时就要解析我们的cookie了。其实在之前我们登录之前,在这个事件代码中也解析了cookie的,只是那时候没有找到cookie而以。

  Application_AuthenticateRequest事件的代码中,其实就是解析cookie,然后把用户的身份标识,并且把用户的身份信息保存起来:

Code
  Code
  Code
  void Application_AuthenticateRequest(object sender, EventArgs e)
  {
  HttpApplication app = (HttpApplication)sender;
  //获取身份验证的cookie
  HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
  if (cookie != null)
  {
  string encryptedTicket = cookie.Value;
  //解密cookie中的票据信息
  FormsAuthenticationTicket ticket =
  FormsAuthentication.Decrypt(encryptedTicket);
  //获取用户角色信息
  string[] roles = new string[]{ticket.UserData.toString()};
  //创建用户标识
  FormsIdentity identity = new FormsIdentity(ticket);
  //创建用户的主体信息
  System.Security.Principal.GenericPrincipal user =
  new System.Security.Principal.GenericPrincipal(identity, roles);
  app.Context.User = user;
  }
  }


  我们看到最后一行代码:app.Context.User = user;,把用户的身份以及角色信息保存在了User属性中。

  我们就可以在页面中通过如下方法判断用户是否登录了:

if (Page.User.Identity.IsAuthenticated)
  {
  //
  }


  用下面的方法判断用户是否属于某个角色:

  if (Page.User.IsInRole("Admin")
  {
  //
  }


  其实这个我们之前讲过了的Identity,IPrincipal概念有关,不清楚的可以看看之前的文章!

原文地址:https://www.cnblogs.com/Leo_wl/p/1893266.html