彻底解决Forms验证角色(roles)问题

这个问题是我在做项目的时候遇到的,因为以前都是用seesion来处理类似的问题,但是有朋友说用Forms可以减少很多代码,由于技术有限,研究了很久,工夫不负有心人,在csdn多位大大的帮助下,特别是[only_endure]大人的细心+耐心的回答才得以有今天的文章,真是感动啊~

闲话就说到此为止,我们知道windows自带的有四种认证方式,是不是四种呢?去baidu下,我们今天只讲关于Form的验证问题;

web.config配置文件先这样写

<authentication mode="Forms">
    <forms name=".AUHENAPSX" loginURL="login.aspx" timeout="30" path="All"></forms>
</authentication>
见文章最后 完成配置

首点我们第一步要做的就是 创建一个login.aspx页面,用来作为此次程序的登陆页,这不是废话吗,没登陆页我验证什么,页面上拉上两textBox,一个用于 用户名 一个用于 密码,再拖一个 DropDownList 在Collection里直接创建两用户组,个人用户|企业用户 我们重要围绕讲的是当用户选择 的是企业用户的时候, 还需要对用户名进行角色的区别~也是我这些天来辛苦的原因。 最后在拖一个 button;我是把整个登陆放在一个用户控件里完成的

碍于篇幅,前台代码略……:)

c#代码:

 

[csharp] view plaincopy
 
using System.Data;  
using System.Configuration;  
using System.Collections;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  
  
public partial class LoginControl : System.Web.UI.UserControl  
{  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (DBO.Login_Role() == "0")  
        {  
            return;  
        }  
        //else  
        
//{  
        
//    UserList u = new UserList();  
        
//    if (DBO.isRole("c_test"))  
        
//    {  
        
//        this.lblType.Text = "<li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
        
//        this.lblType.Text = this.lblType.Text + "您现在是本站的[试用会员]";  
        
//    }  
        
//    if (DBO.isRole("c_normal"))  
        
//    {  
        
//        this.lblType.Text = "</li><li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
        
//        this.lblType.Text = this.lblType.Text + "您现在是本站的[正式会员]";  
        
//    }  
        
//    if (DBO.isRole("c_end"))  
        
//    {  
        
//        this.lblType.Text = "</li><li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
        
//        this.lblType.Text = this.lblType.Text + "您的会员服务已经到期";  
        
//    }  
        
//    this.lblType.Text = this.lblType.Text + "</li><li><a href="login_out.aspx">我要退出</a>";  
        
//}  
    }  
    protected void login_ServerClick(object sender, EventArgs e)  
    {  
        UserList u = new UserList();  
        u.Username = this.txtUserName.Value.Trim();  
        u.Userpass = this.txtUserPass.Value.Trim();  
        string md5 = DBO.MD5_Method(u.Userpass);  
        if (this.ddlType.SelectedValue == "1")  
        {  
            //处理个人用户  
        }  
        else if (this.ddlType.SelectedValue == "2")  
        {  
            DBO.checkCompany(u.Username);  
            if (DBO.isRole("c_test"))  
            {  
                this.lblType.Text = "</li><li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
                this.lblType.Text = this.lblType.Text + "您现在是本站的[试用会员]";  
            }  
            if (DBO.isRole("c_normal"))  
            {  
                this.lblType.Text = "</li><li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
                this.lblType.Text = this.lblType.Text + "您现在是本站的[正式会员]";  
            }  
            if (DBO.isRole("c_end"))  
            {  
                this.lblType.Text = "</li><li>欢迎回来:<span style="COLOR: #f00">" + u.Username + "</span></li><li><a href="company_center.aspx">进入企业用户管理中心</a>";  
                this.lblType.Text = this.lblType.Text + "您的会员服务已经到期";  
            }  
            this.lblType.Text = this.lblType.Text + "</li><li><a href="login_out.aspx">我要退出</a>";  
        }  
    }  
}  
</li>  

 

 以上为 登陆的用户空间的c#代码

DB类的代码

[csharp] view plaincop
using System;  
using System.Data;  
using System.Configuration;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  
using System.Data.SqlClient;  
  
/// <summary></summary>  
/// DBO 的摘要说明  
///   
public class DBO  
{  
    public DBO()  
    {  
        //  
        
// TODO: 在此处添加构造函数逻辑  
        
//  
    }  
  
    public static SqlConnection CreateConn()  
    {  
        return new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ToString());  
    }  
  
    public static string Login_Role()  
    {  
        return HttpContext.Current.User.Identity.Name;  
    }  
  
    public static string UserRole(string username, string roles)  
    {  
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(1.0), false, roles,FormsAuthentication.FormsCookieName);  
        string str = FormsAuthentication.Encrypt(ticket);  
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, str);  
        cookie.Expires = ticket.Expiration;  
        HttpContext.Current.Response.Cookies.Add(cookie);  
        return FormsAuthentication.GetRedirectUrl(FormsAuthentication.FormsCookieName, false);  
    }  
  
    public static bool isRole(string role)  
    {  
        return HttpContext.Current.User.IsInRole(role);  
    }  
  
    public static string MD5_Method(string userpass)  
    {  
        return FormsAuthentication.HashPasswordForStoringInConfigFile(userpass, "MD5");  
    }  
  
    public static void Logout()  
    {  
        HttpCookie cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];  
  
        if (cookie == null)  
        {  
            cookie = new HttpCookie(FormsAuthentication.FormsCookieName);  
            HttpContext.Current.Response.Cookies.Add(cookie);  
        }  
        cookie.Expires = DateTime.Now.AddYears(-10);  
    }  
  
  
    public static void checkCompany(string username)  
    {  
        SqlConnection connection = DBO.CreateConn();  
        SqlDataAdapter adapter = new SqlDataAdapter("select usertype,end_time from company where username='" + username + "'", connection);  
        DataSet ds = new DataSet();  
        adapter.Fill(ds);  
        string strType = ds.Tables[0].Rows[0]["usertype"].ToString();  
        string strSpan = ds.Tables[0].Rows[0]["end_time"].ToString();  
  
        if (strType == "0")  
        {  
            DBO.UserRole(username, "c_test");  
        }  
        else  
        {  
            DateTime now=DateTime.Now;  
            TimeSpan span=(TimeSpan)(DateTime.Parse(strSpan)-now);  
            if (span.Hours > 0)  
            {  
                DBO.UserRole(username, "c_normal");  
            }  
            else  
            {  
                DBO.UserRole(username, "c_end");  
            }  
        }  
    }  

}   

 MemberShip类代码

[csharp] view plaincopy
using System;  
using System.Data;  
using System.Configuration;  
using System.Web;  
using System.Web.Security;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Web.UI.WebControls.WebParts;  
using System.Web.UI.HtmlControls;  
using System.Security;  
using System.Security.Principal;  
  
/// <summary></summary>  
/// MemberShip 的摘要说明  
///   
public class MemberShip : IHttpModule  
    {  
        public void Init(HttpApplication app)  
        {  
            app.AuthenticateRequest += new EventHandler(app_AuthenticateRequest);  
            app.EndRequest += new EventHandler(app_EndRequest);  
        }  
  
        void app_EndRequest(object sender, EventArgs e)  
        {  
            foreach (string key in HttpContext.Current.Response.Cookies)  
            {  
                HttpContext.Current.Response.Cookies[key].Domain = ConfigurationManager.AppSettings["domain"];//这里可以保证你的cookie都是顶级域名下的,可以实现二级域名,N级域名登录  
            }  
        }  
  
        public void Dispose() { }  
  
        private void app_AuthenticateRequest(object sender, EventArgs e)  
        {  
            // 提取窗体身份验证 cookie  
            string cookieName = FormsAuthentication.FormsCookieName;  
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];  
  
            if (null == authCookie)  
            {  
                // 没有身份验证 cookie。  
                return;  
            }  
  
            FormsAuthenticationTicket authTicket = null;  
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);  
  
            if (null == authTicket)  
            {  
                // 无法解密 Cookie。  
                return;  
            }  
            // 创建票证后,为 UserData 属性指定一个  
            
// 以管道符分隔的角色名字符串。  
            string[] roles = authTicket.UserData.Split(new char[] { ',' });  
  
  
            // 创建一个标识对象  
            FormsIdentity id = new FormsIdentity(authTicket);  
  
            // 该主体将通过整个请求。  
            GenericPrincipal principal = new GenericPrincipal(id, roles);  
            // 将新的主体对象附加到当前的 HttpContext 对象  
            HttpContext.Current.User = principal;  
        }  

    }   

  1. <!--l version="1.0--><?xml version="1.0"?><br><!-- <br>    注意: 除了手动编辑此文件以外,您还可以使用 <br>    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的<br>     “网站”->“Asp.Net 配置”选项。<br>    设置和注释的完整列表在 <br>    machine.config.comments 中,该文件通常位于 <br>    /Windows/Microsoft.Net/Framework/v2.x/Config 中<br>--><br><configuration><br> <appSettings/><br>  <connectionStrings><br>    <add name="ConString" connectionString="Data Source=(local); Initial Catalog=AjaxTalent; user id=sa; pwd=sa" providerName="System.Data.SqlClient;"/><br>  </connectionStrings><br> <system.web><br><br>    <authentication mode="Forms"><br>      <forms name=".authenASPX" loginUrl="login.aspx" timeout="30" protection="All" ></forms><br>    </authentication><br><br>    <httpModules><br>      <add name="MemberShip" type="MemberShip"/><br>    </httpModules><br> </system.web><br>  <location path="Manager"><br>    <system.web><br>      <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="zh-CN"/><br>      <authorization><br>        <allow roles="admin"/><br>        <deny users="*"/><br>      </authorization><br>    </system.web><br>  </location><br></configuration>  
posted @ 2013-01-21 11:01  rains  阅读(315)  评论(0编辑  收藏  举报