彻底解决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#代码:

 

using System;
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 = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; // this.lblType.Text = this.lblType.Text + "您现在是本站的[试用会员]"; // } // if (DBO.isRole("c_normal")) // { // this.lblType.Text = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; // this.lblType.Text = this.lblType.Text + "您现在是本站的[正式会员]"; // } // if (DBO.isRole("c_end")) // { // this.lblType.Text = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; // this.lblType.Text = this.lblType.Text + "您的会员服务已经到期"; // } // this.lblType.Text = this.lblType.Text + "
  • 我要退出"; //} } 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 = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; this.lblType.Text = this.lblType.Text + "您现在是本站的[试用会员]"; } if (DBO.isRole("c_normal")) { this.lblType.Text = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; this.lblType.Text = this.lblType.Text + "您现在是本站的[正式会员]"; } if (DBO.isRole("c_end")) { this.lblType.Text = "
  • 欢迎回来:" + u.Username + "
  • 进入企业用户管理中心"; this.lblType.Text = this.lblType.Text + "您的会员服务已经到期"; } this.lblType.Text = this.lblType.Text + "
  • 我要退出"; } } }

 

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

DB类的代码

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;

/// 
/// 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类代码

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;

/// 
/// 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;
        }
    }

 

 web.config配置文件

 
 <?xml version="1.0"?>
<!--
    注意: 除了手动编辑此文件以外,您还可以使用
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”->“Asp.Net 配置”选项。
    设置和注释的完整列表在
    machine.config.comments 中,该文件通常位于
    /Windows/Microsoft.Net/Framework/v2.x/Config 中
-->
<configuration>
 <appSettings/>
  <connectionStrings>
    <add name="ConString" connectionString="Data Source=(local); Initial Catalog=AjaxTalent; user id=sa; pwd=sa" providerName="System.Data.SqlClient;"/>
  </connectionStrings>
 <system.web>

    <authentication mode="Forms">
      <forms name=".authenASPX" loginUrl="login.aspx" timeout="30" protection="All" ></forms>
    </authentication>

    <httpModules>
      <add name="MemberShip" type="MemberShip"/>
    </httpModules>
 </system.web>
  <location path="Manager">
    <system.web>
      <globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="zh-CN"/>
      <authorization>
        <allow roles="admin"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
</configuration>
在这个过程中我所遇到的问题就是当cookie保存进客户端的时候,却不知道让他一直存在我们的程序内,用
一个asp.net 的内置方法 HttpContext.Current.User.IsInRole(string role);  来判断当前用户
名是属于哪个分组,后来才知道是不能直接用FormsAuthenticationTicket这个类保存的cookie和
User.IsInRole()做映射,需要在中间放一个中间类,来建议映射,这个类就是上面的 MemberShip 相关的
方法请查阅msdn就可以知道原理了~ 希望能和大家继续讨论~ 谢谢
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值