Asp.Net Forms 身份验证

Web系统登录,身份认证,以及验证登录过期都是基本常用的,写了一个,就发出来吧。

水平有限,代码写的烂,轻喷。

1,新建Web项目,新建UserInfo类

    public class UserInfo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Password { get; set; }
    }

2,登录实现代码,代码很简单:

   protected void Button1_Click(object sender, EventArgs e)
        {
            string username = txtName.Text.Trim();
            string pass = txtPwd.Text.Trim();

            if (!string.IsNullOrEmpty(username))
            {
                if (!string.IsNullOrEmpty(pass))
                {
                    UserInfo user = UserLogon(username, pass);
                    if (user != null)
                    {
                        string userdata = string.Format("{0},{1},{2}", user.Id, user.Name, user.Password);

                        //Forms身份认证的标示
                        FormsAuthenticationTicket ticket =
                            new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddSeconds(40), true, userdata);

                        //加密
                        string encticket = FormsAuthentication.Encrypt(ticket);

                        //创建Cookie
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encticket);

                        Response.Cookies.Add(cookie);

                        Response.Redirect("Index.aspx");
                    }
                }
            }
        }

        private UserInfo UserLogon(string name, string pwd)
        {
            UserInfo user = null;
            if (name == "admin")
            {
                user = new UserInfo { Id = 1, Name = "admin", Password = "123456" };
            }

            return user;
        }

用户信息也可自行加密。

3,获取当前用户信息:

 protected void Page_Load(object sender, EventArgs e)
        {
            UserInfo model = GetCookieUser();

            this.divuser.InnerHtml = model.Id + "<br />" + model.Name + "<br />" + model.Password;
        }


   private UserInfo GetCookieUser()
        {
            UserInfo user = new UserInfo();
            FormsIdentity identity = HttpContext.Current.User.Identity as FormsIdentity;
            FormsAuthenticationTicket ticket = identity.Ticket;
            
            string userdata = ticket.UserData; //获取自定义的 UserData 串
            if (!string.IsNullOrEmpty(userdata))
            {
                string[] uinfo = userdata.Split(',');
                user.Id = int.Parse(uinfo[0]);
                user.Name = HttpContext.Current.User.Identity.Name;
                user.Password = uinfo[2];
            }

            return user;
        }

 4,最后配置文件修改,配置文件相关节点属性,可自行查阅:

<configuration>
  <system.web>
    <authentication mode="Forms">
      <!--认证-->
      <forms loginUrl="Login.aspx" defaultUrl="Index.aspx" name="TestAuth" path="/"
             slidingExpiration="true" timeout="30" protection="All">
      </forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>
    <!--加密方式-->
    <machineKey decryption="Auto" validation="SHA1"/>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
</configuration>

现在身份认证已经完成,不登录,不是admin都无法访问Index.aspx页面,会直接跳转到Login.aspx 登录页面。

至此,简单的登录,认证,过期登出操作完成,在此只做简单说明,至于其他可自行扩展。

原文地址:https://www.cnblogs.com/softmax/p/3639528.html