ASP.NET Forms身份认证

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了ASP.NET Forms身份认证脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

项目结构如下图:

根目录 Web.config 代码:

<&#63;XMl version="1.0" encoding="utf-8"?>
<!--
 有关如何配置 ASP.NET 应用程序的详细消息,请访问
 http://go.microsoft.COM/fwlink/?LinkId=169433
 -->
<configuration>
  <System.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
     <forms loginUrl="LOGin.aspx"></forms>
    </authentication>
    <!--<authorization>
     <allow users="*"></allow>
    </authorization>-->
  </system.web>
</configuration>

admin文件夹中 Web.config 代码:

<?xML version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="admin" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

teacher文件夹中 Web.config 代码:

<?xml version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="teacher" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

student文件夹中 Web.config 代码:

<?xml version="1.0"?>
<configuration>
 <system.web>
 <authorization>
 <allow roles="student" />
 <deny users="*"/>
 </authorization>
 </system.web>
</configuration>

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

PRotected void SetLoginCookie(string username, string roles)
{
System.Web.SecurITy.FormsAuthentication.SetAuthCookie(username, false);
 System.Web.Security.FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), false, roles, "/");
 string hashTicket = FormsAuthentication.Encrypt(ticket);
 HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
 HttpContext.current.Response.SetCookie(userCookie);
}

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); //这样当前用户就拥有角色信息了
 }
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的ASP.NET Forms身份认证全部内容,希望文章能够帮你解决ASP.NET Forms身份认证所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。