热门:网页模板.net视频教程JQueryMVCjsonExtJs源码示例三级联动JQuery菜单
您现在的位置:.Net中文社区>> .Net编程>>正文内容

.Net基于Forms认证

发布时间:2009年10月28日点击数: xiaoxiaoniao

最近看了下表单认证,又练习了下,现总结下来供大家参考,希望对大家有用吧 !

1:web.config配置

   <authentication mode="Forms">
      <forms name=".culbWeb"  defaultUrl="login.aspx" cookieless="UseCookies" protection="All" timeout="30" path="/"/>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

2:login.aspx文件

 protected void btnLogin_Click(object sender, EventArgs e)
    {

        if(userid>0) //说明该用户存在

{

        //登陆成功!
        SetAuthCookie(Textbox1.Text, false, userid);
        Response.Redirect(GetRedirectUrl(Textbox1.Text, false));

}
    }

3: 涉及到的方法

  if (userID <= 0)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
        else
        {
            if (!HttpContext.Current.Request.IsSecureConnection && FormsAuthentication.RequireSSL)
                throw new HttpException("Connection_not_secure_creating_secure_cookie");
            string userdata = userID.ToString() ;//userRole only one char
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2,
                userName, DateTime.Now, DateTime.Now.AddMinutes(20), createPersistentCookie,
                userdata, FormsAuthentication.FormsCookiePath);

            // Encrypt the ticket.
            string encTicket = FormsAuthentication.Encrypt(ticket);
            if (string.IsNullOrEmpty(encTicket))
                throw new HttpException("Unable_to_encrypt_cookie_ticket");
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            cookie.HttpOnly = true;
            cookie.Path = FormsAuthentication.FormsCookiePath;
            cookie.Secure = FormsAuthentication.RequireSSL;
            if (FormsAuthentication.CookieDomain != null)
            {
                cookie.Domain = FormsAuthentication.CookieDomain;
            }
            if (ticket.IsPersistent)
            {
                cookie.Expires = ticket.Expiration;
            }

            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
    public  string GetRedirectUrl(string userName, bool createPersistentCookie)
    {
        string url = FormsAuthentication.GetRedirectUrl(userName, createPersistentCookie);
        return url;
    }

本站热点业务

更多模板/案例展示

关于我们 | 联系我们 | 团队日志 | 网站地图 | 网站合作