>  기사  >  백엔드 개발  >  ASP.NET 양식 인증

ASP.NET 양식 인증

高洛峰
高洛峰원래의
2017-02-10 17:09:061259검색

asp.net 프로그램에서 사용자는 자신의 역할에 따라 해당 페이지와 기능에 액세스할 수 있습니다. 이번 글에서는 참고할만한 아주 좋은 내용을 소개하겠습니다.

asp.net 프로그램 개발에 대해 살펴보겠습니다. 사용자는 자신의 역할에 따라 해당 페이지와 기능에 액세스합니다.

프로젝트 구조는 다음과 같습니다.

ASP.NET Forms身份认证

루트 디렉터리 Web.config 코드:


<?xml version="1.0" encoding="utf-8"?>
<!--
 有关如何配置 ASP.NET 应用程序的详细消息,请访问
 http://www.php.cn/
 -->
<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>


관리 폴더의 Web.config 코드:


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


교사 폴더의 Web.config 코드:


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


학생 폴더의 Web.config 코드:


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


로그인 .aspx에 로그인 성공 후 쿠키 설정, 쿠키 코드 설정:


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(&#39;,&#39;); //将角色数据转成字符串数组,得到相关的角色信息 
 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了
 }
 }
}

ASP.NET Forms 신원 인증과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.