关于新手最容易上手的ASP.NET基于角色的窗体安全认证机制 Demo

第一步:数据库建表测试用 (以下代码直接copy在t-sql下生成即可)

Create DATABASE WebSolution
GO
USE [WebSolution]
GO
/****** 对象:  Table [dbo].[Users]    脚本日期: 04/07/2016 15:16:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Users](
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
[Password] [nvarchar](150) COLLATE Chinese_PRC_CI_AS NULL,
[UserRoles] [nvarchar](100) COLLATE Chinese_PRC_CI_AS NULL,
 CONSTRAINT [PK__Users__00551192] PRIMARY KEY CLUSTERED 
(
[ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


第二步:编写代码

创建一个空解决方案,添加一个web应用程序,应用程序下面有login.aspx、default.aspx、webForm1、Global.aspx、Webconfig

如下图:


login.aspx 页面 button1_Click 事件代码如下:

string strcon = "Data Source=.;Initial Catalog=WebSolution;Persist Security Info=True;User ID=sa;Password=123;";
        protected void Button1_Click(object sender, EventArgs e)
        {
            FormsAuthentication.Initialize();

            SqlConnection conn = new SqlConnection(strcon);
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select UserRoles from Users where userName=@username" +" and Password=@password ";
            cmd.Parameters.Add("@username", SqlDbType.NVarChar, 100).Value = this.TextBox1.Text;
            cmd.Parameters.Add("@password", SqlDbType.NVarChar, 150).Value = FormsAuthentication.HashPasswordForStoringInConfigFile(this.TextBox2.Text, "md5");
            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, this.TextBox1.Text.ToString(), DateTime.Now, DateTime.Now.AddMinutes(1), true, reader.GetString(0), FormsAuthentication.FormsCookiePath);
                string strticket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strticket);
                if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
                Response.Cookies.Add(cookie);
                string returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl == null)
                {
                    returnUrl = "./";
                }
                Response.Redirect(returnUrl);
                this.Label3.Text = "登陆成功";
            }
            else
            {
                this.Label3.Text = "用户名或者密码错误,请重试!";
            }
            reader.Close();
            conn.Close();
        }
</span>

defalt.aspx Page_Load 事件代码如下:

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (User.IsInRole("Administrator"))
                {
                    Response.Write("你好管理员");
                }
                else if (User.IsInRole("User"))
                {
                    Response.Write("你好会员");
                }
            }
        }
第三步:配置

我们需要修改Global.aspx 文件。如果你的Web应用程序没有这个文件,请右键单击web应用程序,选择"添加->添加新项->Global Application Class"。 在Global.aspx 或者Global.aspx.cs 中,找到Application_AuthenticationRequest的方法。先要确认已经包换或者使用了System.Security.Principal以及System.Web.Security命名空间,然后修改它,修改后的代码:

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{
    if (HttpContext.Current.User != 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);
            }
        }
    }
}

接下来,在Web应用程序根目录下的 Web.config 文件中找到 <system.web> 节点下的


<authentication mode="Windows" />,把它修改为
  <authentication mode="Forms">
      <forms loginUrl="Login.aspx" name=".AMUHOUSE.ASPXAUTH" defaultUrl="Default.aspx" protection="All" path="/">
      </forms>
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>


接下来,在Admin、User文件夹下各添加一个webconfig配置文件


在Admin文件下 <system.web>节点插入代码如下:
 <authorization>
        <!-- 注意!下面几行的顺序和大小写是非常重要的! -->
        <allow roles="Administrator"/>
        <deny users="*"/>
      </authorization>
在User文件下 <system.web>节点插入代码如下:
 <authorization>
        <!-- 注意!下面几行的顺序和大小写是非常重要的! -->
        <allow roles="User"/>
        <deny users="*"/>
      </authorization>
然后再分别在两个文件夹下添加几张图片用来测试用户角色权限,现在代码基本完工。


第四步:测试


• 测试用户名密码分别为  (用户名:admin 密码: pwd123 权限:管理员)(用户名:lisaisai 密码:pwd123 权限:普通会员 )



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三天不学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值