温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET如何实现Forms身份认证

发布时间:2021-08-18 15:14:43 来源:亿速云 阅读:197 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关ASP.NET如何实现Forms身份认证的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

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

项目结构如下图:

ASP.NET如何实现Forms身份认证

根目录 Web.config 代码:

<?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身份认证”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI