[转]几种身份验证的实现

   身份验证,特别是在用户没有登陆的情况下不能访问其他页面的控制,好象总是避免不了。要达到这样的目的,方法其实有很多。
   1.采用session控制。在登陆的时候给session赋值,而后在其他所有页面的Load事件中对session进行判断。这个利用了session针对单用户的特点,实现方法很简单,但是需要每个页面判断,有些不尽人意.
   2.cookie实现。自定义一个基类,用来判断cookie值,并根据具体情况作出一些动作(是继续作业,还是跳转到login).其他页面继承这个类即可.具体实现可参考:http://blog.csdn.net/JustLovePro/archive/2008/04/07/2259296.aspx; http://blog.csdn.net/JustLovePro/archive/2008/04/08/2259369.aspx; 采用这种方式的好处就是非常灵活,因为对cookie的控制都是有我们自己控制的. 单每个页面还是要继承这个基类,要避免这个,就得看MS的了。
  3.Forms身份验证.MS在这里为我们做了大量的工作,我们要做的其实就是简单的配置就好了。然后就是几个已经封装好的类的使用。看代码:
web.config:
  <authentication mode="Forms">
      <forms
       name=".ASPXAUTH"  
       loginUrl ="Login.aspx"
       defaultUrl ="FormsDemo.aspx"
       protection ="All"
       timeout ="30"
       path ="/"
       requireSSL ="false"
       slidingExpiration ="true"
       enableCrossAppRedirects ="false"
       cookieless ="UseDeviceProfile"
       domain =""
      >
             </forms>
  </authentication>
  <authorization>
   <deny users="?"/>
  </authorization>
------------------------------------
Login.cs
  protected void btnLogin_Click(object sender, EventArgs e)
    {
        string username = txtName.Text;
        FormsAuthentication.RedirectFromLoginPage(username, true);
      
    }

---------------------
主页面,显示登陆者信息和注销帐户:
    protected void Page_Load(object sender, EventArgs e)
    {

        if (User.Identity.IsAuthenticated)
        {
            FormsIdentity identity = User.Identity as FormsIdentity;
            FormsAuthenticationTicket ticket = identity.Ticket;
            Response.Write("UserName:" + identity.Name);
            Response.Write("Time" + DateTime.Now.ToString());
        }
        else
        {
            FormsAuthentication.RedirectToLoginPage();
        }
       
    }
    protected void btnsignout_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        FormsAuthentication.RedirectToLoginPage();
    }
 ===============================
就这样,其他页面不用实现任何代码,就可以达到目的。

原文地址:https://www.cnblogs.com/xjyggd/p/1235234.html