ASP.NET Forms身份认证

asp.net程序开发,用户根据角色访问对应页面以及功能。

项目结构如下图:

根目录 Web.config 代码:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <!--
 3   有关如何配置 ASP.NET 应用程序的详细消息,请访问
 4   http://go.microsoft.com/fwlink/?LinkId=169433
 5   -->
 6 <configuration>
 7     <system.web>
 8         <compilation debug="true" targetFramework="4.0" />
 9         <authentication mode="Forms">
10           <forms loginUrl="login.aspx"></forms>
11         </authentication>
12         <!--<authorization>
13           <allow users="*"></allow>
14         </authorization>-->
15     </system.web>
16 </configuration>

admin文件夹中 Web.config 代码:

1 <?xml version="1.0"?>
2 <configuration>
3   <system.web>
4     <authorization>
5       <allow roles="admin" />
6       <deny users="*"/>
7     </authorization>
8   </system.web>
9 </configuration>

teacher文件夹中 Web.config 代码:

1 <?xml version="1.0"?>
2 <configuration>
3   <system.web>
4     <authorization>
5       <allow roles="teacher" />
6       <deny users="*"/>
7     </authorization>
8   </system.web>
9 </configuration>

student文件夹中 Web.config 代码:

1 <?xml version="1.0"?>
2 <configuration>
3   <system.web>
4     <authorization>
5       <allow roles="student" />
6       <deny users="*"/>
7     </authorization>
8   </system.web>
9 </configuration>

Login.aspx中登录成功后设置Cookie,设置Cookie代码:

1 protected void SetLoginCookie(string username, string roles)
2 {
3     System.Web.Security.FormsAuthentication.SetAuthCookie(username, false);
4     System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), false, roles, "/");
5     string hashTicket = FormsAuthentication.Encrypt(ticket);
6     HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
7     HttpContext.Current.Response.SetCookie(userCookie);
8 }

Global.asax 中进行身份验证:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象  
    if (ctx.User != null)
    {
        if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证  
        {
            System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity;
            System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票  
            string userData = ticket.UserData;//从UserData中恢复role信息
            string[] roles = userData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息  
            ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了
        }
    }
}

 

posted @ 2017-02-04 16:40  木子陽  阅读(486)  评论(0编辑  收藏  举报