第一步:数据库建表测试用 (以下代码直接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 权限:普通会员 )