Forms验证

登陆页:

namespace Booksir.Domain.Web
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnLogin_Click(object sender, AjaxEventArgs e)
        {
            string UserName = this.txtUserName.Text;
            string UserPwd = this.txtPassWord.Text;
            UserBll userbll = new UserBll();
            if (this.rAgent.Checked)
            {
                if (userbll.LoginUser(UserName, UserPwd, 0))
                {
                    UserLogin(UserName, UserPwd, 0
                }
                else
                {
                    Ext.Msg.Alert("登陆错误", "用户名或密码出现错误!").Show();
                }
            }
            else if (this.rEmployee.Checked)
            {
                if (userbll.LoginUser(UserName, UserPwd, 1))
                {
                    UserLogin(UserName, UserPwd, 1);
                }
                else
                {
                    Ext.Msg.Alert("登陆错误", "用户名或密码出现错误!").Show();
                }
            }
            else
            {
                Ext.Msg.Alert("登陆错误", "用户名或密码出现错误!").Show();
            }
        }

namespace Booksir.Domain.Web.webBll
{
    public class BasePage:System.Web.UI.Page
    {
        public void UserLogin(string UserName, string UserPwd, int URole)
        {
            string userInfo = UserName + "|" + URole.ToString();
            string userURole = URole.ToString().Trim();
            FormsAuthenticationTicket Ticket = null;
            Ticket = new FormsAuthenticationTicket(1, userInfo, DateTime.Now, DateTime.Now.AddHours(88888), false, userURole, "/");
            string HashTicket = FormsAuthentication.Encrypt(Ticket);
            //生成客户端Cookie
            HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);

            Context.Response.Cookies.Add(UserCookie);
            if (Context.Request["ReturnUrl"] != null)
                Context.Response.Redirect(Context.Request["ReturnUrl"]);
            else
                System.Web.HttpContext.Current.Response.Redirect("Default.aspx");
        }

        public static string[] GetUserInfo()
        {
            return HttpContext.Current.User.Identity.Name.Split('|');
        }

    }
}


    }
}

 

test.aspx页代码:

 

读出来:

using System.Web.UI;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Booksir.Domain.Web
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Write(GetUserInfo()[1].ToString());
        }
        public static string GetUserRole()
        {
            FormsIdentity Id = (FormsIdentity)HttpContext.Current.User.Identity;
            //取得身份验证票
            FormsAuthenticationTicket Ticket = Id.Ticket;
            //设置用户角色
            return Ticket.UserData;
        }
        public static string[] GetUserInfo()
        {
            return HttpContext.Current.User.Identity.Name.Split('|');
        }
    }
}

 

web.config配置

    <authentication mode="Forms">
      <forms loginUrl="Login.aspx" name="BooksirDomain" protection="All" timeout="20" path="/"></forms>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

 

 

 

接下来是别人的一个实例:

 

户文件夹(我们暂定user文件夹):只有用户登录以后才能访问。否则该访客只能访问user文件夹的登录页面(user_login.aspx)
管理员文件夹( 暂定admin文件夹):管理员文件夹不让任何人服务,当用户登录以后只能访问管理员登陆页(admin_login.aspx),管理员登陆后才能访问全部页面。
根目录:根目录可以让任何人访问。

目录结构如下:


第一步:
    根目录下config代码:
     <authentication mode="Forms">    
       <forms name="UserCookies" loginUrl="Default.aspx"></forms>
      </authentication>
      <authorization>
        <allow users="*"/>
      </authorization>

第二部:
    Global.asax
    头部添加
     <%@ Import Namespace="System.Security.Principal" %>


     void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            //如果用户通过验证,则该项不为null
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                    FormsAuthenticationTicket ticket = id.Ticket;

                    string userData = ticket.UserData;//取出角色数据
                    string[] roles = userData.Split(',');
                    HttpContext.Current.User = new GenericPrincipal(id, roles);//重新分配角色
                }
            }
        }
    }

 

第三部:
admin文件夹config 文件

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings/>
<connectionStrings/>
<location path="admin_login.aspx">
    <system.web>
      <authorization>
        <allow roles="user"/>
      </authorization>
    </system.web>
</location>
<system.web>
    <authorization>
      <allow roles="admin"/>
      <deny users="*"/>
    </authorization>
</system.web>
</configuration>

admin_login.aspx


cs 代码如下:
protected void Button1_Click(object sender, EventArgs e)
    {
        if (tbUserName.Text == "xiaomiao")
        {
            //生成验证票据,其中包括用户名、生效时间、过期时间、是否永久保存和用户数据等。而关于用户角色的信息,我们保存在用户数据中。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), true, "Admin");
            string cookieStr = FormsAuthentication.Encrypt(ticket);//对票据进行加密
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
            /*保存到cookie中。cookie的名字要与我们前面在配置文件中所写的name值一样。因为,当cookie保留在本地后,下次再检查用户权限的时候就会自动查找与forms名称相同的cookie,并传送给服务器端进行检验。如果在本地找不到cookie,就自然无法通过验证。*/
            cookie.Expires = ticket.Expiration;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(cookie);
            Response.Redirect("default.aspx");//登陆成功后跳转到index.aspx
        }
    }


第四步:

user文件夹config代码
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings/>
    <connectionStrings/>
<location path="user_login.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
</location>
    <system.web>
      <authorization>
        <allow roles="user,admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
</configuration>

user_login.aspx

CS代码:
protected void Page_Load(object sender, EventArgs e)
    {
        //判断用户是否已经登陆,且角色为user
        if (User.Identity.IsAuthenticated && User.IsInRole("user"))
        {//如果通过验证,则直接跳转到index.aspx
            Response.Redirect("default.aspx");
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (tbUserName.Text == "xiaomiao")
        {
            //生成验证票据,其中包括用户名、生效时间、过期时间、是否永久保存和用户数据等。而关于用户角色的信息,我们保存在用户数据中。
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbUserName.Text, DateTime.Now, DateTime.Now.AddMinutes(30), true, "User");
            string cookieStr = FormsAuthentication.Encrypt(ticket);//对票据进行加密
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr);
            /*保存到cookie中。cookie的名字要与我们前面在配置文件中所写的name值一样。因为,当cookie保留在本地后,下次再检查用户权限的时候就会自动查找与forms名称相同的cookie,并传送给服务器端进行检验。如果在本地找不到cookie,就自然无法通过验证。*/
            cookie.Expires = ticket.Expiration;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            Response.Cookies.Add(cookie);
            Response.Redirect("default.aspx");//登陆成功后跳转到index.aspx
        }

    }

 

 

posted @ 2010-09-06 16:02  咸鱼公子  Views(1146)  Comments(1Edit  收藏  举报