Pages

Tuesday, August 26, 2014

ASP.Net Forms Authentication

<configuration>
<system.web>
<authenticationmode="Forms"/>
<authorization>
<deny users = "?" /> ------------- deny all anonymous users
</authorization>
</system.web>
</configuration>

If anonymous access the Default.aspx page, then its redirected to Login.aspx (this is default by rule).

Login_Click()
{
if(IsAuthenticateUser(username, password)) ) -- does the dB lookup validation
{
FormsAuthentication.RedirectFromLoginPage(username, true) -- true means cookie is stored in hard disk. false means cookie is stored in browser.
}
else
{
Invaid user
}
}

LogOut_Click()
{
FormsAuthentication.Signout();
}

User logs into applciation, get the Cookie from the Browser and the Harddisk. Change his User privilege to Admin privilege.......
You are protected by ASP.net, dont worry

ASP.Net

     1                                           2                                          3
SecretKey + ASP.Net hashes Cookie content += Message Authentication code

2 and 3 are stored in cookie... any alteration the User does to the cookie, ASP.net can identify by doing check sum for 1 and 2 and checks the 3 is been is retiried correctly.

Its wise to program in in terms of Roles but Users  -- User.IsInRole("Doctors")

<configuration>
   <system.web>
      <authenticationmode="Forms"/>
      <authorization>
          <deny users = "?" /> ------------- deny all anonymous users
      </authorization>
   </system.web>
</configuration>

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

In Global.asax, setup the roles for logged in User in the Init() method

Global.ascx.cs
public override void Init()
{
     AuthenticateRequest += new EvenHandler(Global_AuthenticateRequest)
      // AuthenticateRequest -- rip apart the Cookie and give the Identity. This will run after all the  
        Modules were run. (ex: Form Authentication)
}

void Global_AuthenticateRequest(object sender, EventArgs e)
{
     if(Request.IsAuthenticated)
          SetupRoles();
}

void SetupRoles()
{
        IIdentity formsIdentity = Context.User.Identity();
        string[] roles = LookupForRoles(formIdentity.Name); // Get the Roles of the user
        IPrincipal principalWithRoles = new GenericPrincipal(formIdentity, roles);
        Context.User = principalWithRoles;
        Context.Items["roles"] = roles;
}



 

No comments:

Post a Comment