asp.net Forms身份验证和基于角色的权限访问(2)


        protected void btnLogin_Click(object sender, EventArgs e)
        {    
            //Forms身份验证初始化
            FormsAuthentication.Initialize();
            //验证用户输入并得到登录用户,txtName是用户名称,txtPassword是登录密码
            UserModel um = ValidUser(txtName.Text.Trim(),txtPassword.Text.Trim());
            if (um != null)
            {
             //创建身份验证票据
             FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
                                            um.Name,
                                            DateTime.Now,
                                            DateTime.Now.AddMinutes(30),
                                            true,
                                            um.Roles,//用户所属的角色字符串
                                            FormsAuthentication.FormsCookiePath);
             //加密身份验证票据
             string hash = FormsAuthentication.Encrypt(ticket);
             //创建要发送到客户端的cookie
             HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
             if (ticket.IsPersistent)
             {
                cookie.Expires = ticket.Expiration;
             }
             //把准备好的cookie加入到响应流中
             Response.Cookies.Add(cookie);

             //转发到请求的页面
             Response.Redirect(FormsAuthentication.GetRedirectUrl(um.Name,false));
            }
            else
            {
             ClientScriptManager csm = this.Page.ClientScript;
             csm.RegisterStartupScript(this.GetType(), "error_tip", "alert('用户名或密码错误!身份验证失败!');", true);
            }
        }    
        //验证用户
        private UserModel ValidUser(string name, string password)
        {
            return new UserService().Validate(name, password);
        }


    4、给网站添加处理程序Global.asax,其中通用身份验证代码如下:

复制代码 代码如下:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjfywz.html