做项目的时候经常需要权限认证,我实践了,做下笔记。
Web.Config
<system.web>
<!--通过 <authentication> 节可以配置 ASP.NET 用来识别进入用户的安全身份验证模式。-->
<authentication mode="Forms">
<forms name="AspxAuth" loginUrl="/Login.aspx" timeout="30" protection="All" path="/">
</forms>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
登陆页面的代码:
FormsAuthentication.Initialize();
string userRoles =“角色"; //调用UserToRole方法来获取role字符串
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, userRoles, "/"); //建立身份验证票对象
string HashTicket = FormsAuthentication.Encrypt (Ticket) ; //加密序列化验证票为字符串
HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket) ;
//生成Cookie
Context.Response.Cookies.Add (UserCookie) ; //输出Cookie
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket);
if (Ticket.IsPersistent)
{
cookie.Expires = Ticket.Expiration;
}
//把准备好的cookie加入到响应流中
Response.Cookies.Add(cookie);
//转发到请求的页面
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, false));
else
{
Context.Response.Redirect("Main");
}
Global.asax文件
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication App = (HttpApplication)sender;
HttpContext Ctx = App.Context; //获取本次Http请求相关的HttpContext对象
if (Ctx.Request.IsAuthenticated == true) //验证过的用户才进行role的处理
{
FormsIdentity Id = (FormsIdentity)Ctx.User.Identity;
FormsAuthenticationTicket Ticket = Id.Ticket; //取得身份验证票
string[] Roles = Ticket.UserData.Split(','); //将身份验证票中的role数据转成字符串数组
Ctx.User = new GenericPrincipal(Id, Roles); //将原有的Identity加上角色信息新建一个GenericPrincipal表示当前用户,这样当前用户就拥有了role信息
}
}
页面判断是否有权限代码如下:
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
//判断通过身份验证的用户是否是Admin角色
if (!id.Ticket.UserData.Contains("Admin"))
{
//跳转到访问权限不够的错误提示页面
}