ASP.NET基于角色的窗体安全认证机制

一言不合就上demo

 第一步:数据库建表测试用

Create DATABASE WebSolution
GO
USE [WebSolution]
GO

/****** 对象:  Table [dbo].[Users]    脚本日期: 02/15/2012 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.asax、webconfig。

 文件夹Admin、User。具体如下图


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,'用户名', DateTime.Now, DateTime.Now.AddMinutes(1), true,'角色名称', 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();
        }

 Default.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.asax 文件。如果你的Web应用程序没有这个文件,请右键单击Web应用项目,选择 "添加->添加新项...->Global Application Class"。在 Global.asax 或者 Global.asax.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="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>

然后再分别在两个文件夹下添加几张图片用来测试用户角色权限,现在代码基本完工。


还有一种方法形式:

设置info.aspx只有Administrator的角色才可以访问。在根目录的web.config下<system.web>标签下面增加如下配置:

  <location path="Info.aspx">
    <system.web>
      <authorization>
        <allow roles="Administrator"/>
        <deny users="*" />
      </authorization>
    </system.web>
  </location>

表示info.aspx只有administrator角色的会员才能访问。当然如果你想实现文件夹的授权设置,和上面的设置类似在那个文件夹下面的web.config配置一下即可。

第三步:测试

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

  • 未登陆成功前,即未验证用户信息前,登陆任何界面都会强制跳转到登陆界面
  • 登陆后根据角色在主界面显示不同信息
  • 登陆管理员可以访问文件夹Admin里的图片,但不能访问User文件夹里的图片
  • 登陆普通会员可以访问User文件夹里的图片,但不能访问Admin里的图片


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

三天不学习

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

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

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

打赏作者

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

抵扣说明:

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

余额充值