一言不合就上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里的图片