现在的位置: 首页 > 综合 > 正文

Forms身份验证实例

2013年10月21日 ⁄ 综合 ⁄ 共 8094字 ⁄ 字号 评论关闭

1.web.config配置文件

<authentication mode="Forms" >
        <forms loginUrl="~/AdminManage/Login.aspx" name=".loginValidate" path="/" timeout="40" protection="All" />
</authentication>

配置ASP.NET使用的安全身份验证模式,标识传入用户。

 

2.Login.aspx.cs文件

在通过数据库中查询找到相应项后,创建一含票据的Cookie含相关用户信息的Cookie(Info)发送到客户端

...

string[] cookieKey = {"AdminName","lastLoginTime","loginTimes"};

string[] cookieValue = {read["AdminName"].ToString(), read["lastLoginTime"].ToString(), read["loginTimes"].ToString()};

 

SetCookie("Info",cookieKey,cookieValue);

 

AddValidate(read["AdminID"].ToString(),"NetShop_admin");

 

Response.Write("<script>window.location.href='AdminIndex.aspx'</script>");

 

 #region 创建一Cookie集,并发送到客户端
    /// <summary>
    /// 创建一Cookie集,并发送到客户端
    /// </summary>
    /// <param name="cookieName">Cookie集的名称</param>
    /// <param name="cookieKey">Cookie集的键数组</param>
    /// <param name="cookieValue">Cookie集的值数组</param>
    private void SetCookie(string cookieName,string[] cookieKey,string[] cookieValue)
    {
        HttpCookie cookie = new HttpCookie(cookieName);       //创建一Cookie对象

        for (int i = 0; i < cookieKey.Length; i++)        //循环为Cookie对象添加键值对
        {
            cookie.Values.Add(cookieKey[i], cookieValue[i]);
        }

        Response.Cookies.Add(cookie);          //发送到客户端
    }
    #endregion

 

    #region 创建票据验证信息加入Cookie发送到客户端
    /// <summary>
    /// 创建票据验证信息加入Cookie发送到客户端,此处是将票据单独存入一Cookie中
    /// </summary>
    /// <param name="userID">用户名</param>
    /// <param name="userRole">用户角色</param>
    private void AddValidate(string userID, string userRole)
    {
        //创建票据
        FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(
            1,                                  //票据版本号
            userID,                             //要使用的Cookie名(此处使用用户ID编号)

            DateTime.Now,                       //Cookie生成时间
            DateTime.Now.AddMinutes(40),        //Cookie有效时间
            false,                              //是否永久存储
            userRole);                          //用户角色

        //将加密后的票据赋给一string对象cookiestr
        string cookiestr = FormsAuthentication.Encrypt(tkt);

        //创件一Cookie,该Cookie名为存放票据的Cookie名,值为加密后票据值
        HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);
        ck.Path = FormsAuthentication.FormsCookiePath;     //设置与当前Cookie一起传输的虚拟路径

        Response.Cookies.Add(ck);    //发送该包含加密票据的Cookie到客户端
    }
    #endregion

 

3.AdmainIndex.aspx.cs文件

public partial class AdminManage_AdminIndex : NetShop.Page.NetShop_Popedom
{

...

}

使该页面继承自定义页面类NetShop_PopedomNetShop.Page为一命名空间

 

4.页面类NetShop_Popedom.cs文件

namespace NetShop.Page
{
    /// <summary>
    /// NetShop_Popedom 的摘要说明
    /// </summary>
    public class NetShop_Popedom:System.Web.UI.Page
    {
        #region 成员变量
        /// <summary>
        /// 后台管理员编号
        /// </summary>
        protected string AdminID = null;
        /// <summary>
        /// 后台管理员名
        /// </summary>
        protected string AdminName = null;
        /// <summary>
        /// 最后登入时间
        /// </summary>
        protected string lastLoginTime = null;
        /// <summary>
        /// 登入次数
        /// </summary>
        protected string loginTimes = null;
        #endregion

 

        #region 构造函数
        public NetShop_Popedom()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
        #endregion

 

        #region 重定义System.Web.UI.Page中的OnInit事件(初始化页面时调用)
        /// <summary>
        /// 重定义System.Web.UI.Page中的OnInit事件(初始化页面时调用)
        /// </summary>
        protected override void OnInit(EventArgs e)
        {
            #region 显示自定义错误友好提示
            this.Error += new System.EventHandler(PageBase_Error);
            #endregion

 

            #region Form身份验证

            /********获取登入成功后,服务器端发给客户端包含票据的Cookie值,设置相关验证********/

            //获取客户端包含票据的Cookie
            HttpCookie cookie = Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName];

            //#######获取客户端某一Cookie对象     HttpCookie cookie = Request.Cookies["cookieName"];######//

           

            //如果该包含票据的Cookie不为空,用户登入成功
            if (cookie != null)
            {
                //获取该Cookie中的单值即加密的票据信息,因为我们是将票据单独存入一Cookie中发送客户端
                string encryptedTicket = cookie.Value;

                //创建一票据对象,用来自客户端Cookie中获得加密票据值解密后初始化
                System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(encryptedTicket);

                //获取票据中的角色(可能有多个角色)
                string[] roles = new string[] { ticket.UserData };

                //一个使用Forms身份验证的客户端进行了身份验证和标识
                System.Web.Security.FormsIdentity identity = new System.Web.Security.FormsIdentity(ticket);

                //创建用户主体信息
                System.Security.Principal.GenericPrincipal user = new System.Security.Principal.GenericPrincipal(identity, roles);
                HttpContext.Current.User = user;
            }
            else
            {}

 

            /********获取登入成功后,服务器端发给客户端包含客户信息的Cookie,并分析其值********/

            //设置一个Cookie对象以便获取客户端名为"Info"的Cookie值
            HttpCookie InfoCookie = Request.Cookies["Info"];

            //如果用户通过票据验证,且票据中用户角色为NetShop_admin
            if (User.Identity.IsAuthenticated && User.IsInRole("NetShop_admin"))
            {
                string[] adminInfo = User.Identity.Name.Split('|');

                this.AdminID = adminInfo[0];

                AdminName = InfoCookie.Values["AdminName"];
                lastLoginTime = InfoCookie.Values["lastLoginTime"];
                loginTimes = InfoCookie.Values["loginTimes"];
            }
            else
            {
                if (InfoCookie == null)
                {
                    Response.Write("<script>alert('你还没有登录系统!//r//n//r//n请登录系统!');window.location.href = 'Login.aspx';</script>");
                }
                else
                {
                    Response.Cookies["Info"].Expires = DateTime.Now.AddDays(-1);    //将这个Cookie过期掉

                    Response.Write("<script>alert('╯-╰,由于你长时间没有任何操作,身份验证已过期!//r//n//r//n请重新登录系统!');window.location.href='Login.aspx'</script>");
                }

                HttpContext.Current.Response.End();
            }
            #endregion

 

            base.OnInit(e);
        }
        #endregion

 

        #region
        /// <summary>
        /// 更新票据
        /// </summary>
        protected void UpdateNote()
        {
            string userInfo = AdminID;

            System.Web.Security.FormsAuthenticationTicket tkt = new System.Web.Security.FormsAuthenticationTicket(
                1,
                userInfo,
                DateTime.Now,
                DateTime.Now.AddMinutes(40),
                false,
                "admin");

            string cookiestr = System.Web.Security.FormsAuthentication.Encrypt(tkt);

            HttpCookie ck = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName,cookiestr);
            Response.Cookies.Add(ck);

            string[] cookieKey = { "AdminName", "lastLoginTime", "loginTimes" };
            string[] cookieValue = {AdminName, lastLoginTime, loginTimes };

            HttpCookie ckInfo = new HttpCookie("Info");

            for (int i = 0; i < cookieKey.Length; i++)
            {
                ckInfo.Values.Add(cookieKey[i],cookieValue[i]);
            }

            Response.Cookies.Add(ckInfo);
        }
        #endregion

 

        #region 退出系统,删除票据身份验证
        /// <summary>
        /// 退出系统,删除票据身份验证
        /// </summary>
        protected void Esc()
        {
            Response.Cookies["Info"].Expires = DateTime.Now.AddDays(-1);    //将这个Cookie过期掉
            System.Web.Security.FormsAuthentication.SignOut();      //删除客户端的身份验证票据
        }
        #endregion

 

        #region 自定义错误处理
        /// <summary>
        /// 自定义错误处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void PageBase_Error(object sender, System.EventArgs e)
        {
            string errMsg;

            Exception currentError = Server.GetLastError();

            errMsg = "<link rel=/"stylesheet/" href=/"/style.css/">";
            errMsg += "<h1>系统信息:</h1><hr/>系统发生错误, " +
               "<p>该信息已被系统记录,请稍后重试或与管理员联系。</p>" +
               "<p>错误地址: " + Request.Url.ToString() + "</p>" +
               "<p>错误信息: <font class=/"ErrorMessage/">" + currentError.Message.ToString() + "</font></p><hr/>" +
                //"<p>Stack Trace:</b><br/>" + currentError.ToString() + "<p>" +
                "<p><a href=/"javascript:void(0)/" onclick=/"history.go(-1);return false;/">点击此处返回上一页</a></p>"; ;
           
            HttpContext.Current.Response.Write(errMsg);
            HttpContext.Current.Server.ClearError();
        }
        #endregion

抱歉!评论已关闭.