导航

自己的 Form 认证

Posted on 2005-07-25 15:38  美丽软件  阅读(453)  评论(0编辑  收藏  举报
在页面上添加用户名、密码输入框,登录按钮,在登录按钮中添加如下代码
private void BtnLogin_Click(object sender, EventArgs e)
        {
            //Auth the user
            AdminUser adminUser = new AdminUserDao().LoginUser(this.UserName.Text,this.Password.Text);
            if( adminUser != null )
            {
                String[] roles = adminUser.Roles;
                
                StringBuilder sb = new StringBuilder();
                foreach( String role in roles )
                {
                    sb.Append(","+role);
                }

                string userdata = sb.ToString();//以,号分开的用户角色列表
                userdata = userdata.Length>0? userdata.Substring(1):userdata;
                
                FormsAuthenticationTicket ticket =
                    new FormsAuthenticationTicket(
                    1,
                    UserName.Text,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    false,
                    userdata);

                string cookieval = FormsAuthentication.Encrypt(ticket);
                
                HttpCookie cookie = new HttpCookie(
                    FormsAuthentication.FormsCookieName);
                cookie.Value = cookieval;
                cookie.Path = FormsAuthentication.FormsCookiePath;
                //cookie.Expires = DateTime.Now.AddMinutes(30);这样就可以让会话在浏览器关闭后失效
                Response.Cookies.Add(cookie);

                Response.Redirect(FormsAuthentication.GetRedirectUrl(this.UserName.Text,false));
            }
        }

在HttpApplication的AuthenticateReques事件中处理
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            if( Context.User != null && Context.User.Identity.IsAuthenticated )
            {
                HttpCookie authcookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authcookie != null)
                {
                    string cookiedata = authcookie.Value;
                    FormsAuthenticationTicket ticket =
                        FormsAuthentication.Decrypt(cookiedata);
                    string userdata = ticket.UserData;

                    String[] userRoles = userdata.Split(',');
                    GenericIdentity iden = new GenericIdentity(ticket.Name);
                    Context.User = new GenericPrincipal(iden, userRoles);

                    Context.Items["UserRoles"]=userRoles;
                }
            }
        }