Context.User will lose roles after being assigned to Global.asax.Application_AuthenticateRequest

I am using forms authentication in my asp.net application (3.5). I also use roles to determine which user can access these application subdirectories. So the relevant sections of my web.config file look like this:

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Default.aspx" path="/" protection="All" timeout="360" name="MyAppName" cookieless="UseCookies"  />      
  </authentication>
  <authorization >
    <allow users="*"/>
  </authorization>
</system.web>

<location path="Admin">
  <system.web>
    <authorization>
      <allow roles="Admin"/>
      <deny users="*"/>
    </authorization>
  </system.web>
</location>

According to what I read, this should ensure that the only users who have access to the administrator directory are authenticated users who are assigned the administrator role.

, . web.config, . , , .

MS KB -, , Global.asax

protected void Application_AuthenticateRequest(Object sender, EventArgs e) {
    if (HttpContext.Current.User != null) {
        if (Request.IsAuthenticated == true) {    
            // Debug#1            
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value);
            // In this case, ticket.UserData = "Admin"                
            string[] roles = new string[1] { ticket.UserData }; 
            FormsIdentity id = new FormsIdentity(ticket);
            Context.User = new System.Security.Principal.GenericPrincipal(id, roles);
            // Debug#2
        }
    }
}

, , ( ).

, , Context.User.IsInRole( "Admin" ) Debug # 1 , false. Debug # 2, true. , , Global.asax, .

Global.asax ( ). , Page_Load , false. , - Application_AuthenticateRequest Global.asax WebForm , ( : Page_Load - Context.User.Id - ).

, ?


:

+3
2

:

"-" Asp.net. web.config:

<system.web>
  <roleManager enabled="true" />
</system.web>

, Asp.net, FormsAuthentication. , , , .

, web.config, .

+5

, - ? , Admin.

.

( , .

0

Source: https://habr.com/ru/post/1696800/


All Articles