Skip to main content

Using IsInRole() with Forms Authentication

A Little background….

Page object provides User [System.Security.Principal.IPrincipal] in order to access to the information about the current authenticated user. User is having following two important members. These members provide way to implement Role-based authorization programmatically.

Identity [Property] [System.Security.Principal.IPrincipal.Identity] – This property provides important members like AuthenticationType, IsAuthenticated, Name.



IsInRole[Method] [System.Security.Principal.IPrincipal] – This method takes single parameter that is string value of Role for which to check the membership.


First configure the web.config to use Forms Authentication as below:



<authentication mode="Forms">

<forms loginUrl="~/Login/Login.aspx?Session=Expired" protection="None" timeout="20" name=".ASPXAUTH" path="/"/>

</authentication>



On Login click event do the following:





protected void btnLogin_Click(object sender, EventArgs e)

{

/*Here put your code to fetch the userinformation which includes user name, role, password,etc. from Database*/

...



/*Now, create the Forms Authentication ticket with the application’s custom user role & user name,.*/

FormsAuthenticationTicket Authticket = new FormsAuthenticationTicket(1,

userName, DateTime.Now, DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout),

false, userrole.ToString(), FormsAuthentication.FormsCookiePath);



/*You may want to encrypt the ticket information before putting into the coockie.*/

string hash = FormsAuthentication.Encrypt(Authticket);



HttpCookie Authcookie = new HttpCookie          (FormsAuthentication.FormsCookieName, hash);



/*Here you can set some coockie sessings like persistence, httponly..*/

if (Authticket.IsPersistent)

Authcookie.Expires = Authticket.Expiration;



/*Now, add the cookie to the Reponse object of Current HttpContext.*/

HttpContext.Current.Response.Cookies.Add(Authcookie);



/*Put the userrole into session*/

HttpContext.Current.Session[USER_ROLE] = UserRole.Operator;



/*Now you can redirect the user to the requested page*/

HttpContext.Current.Response.Redirect(~/Operator/Home.aspx, false);

}  



Now, you can check the custom application user role on any page before authorizing the resource as follows:



Public static void CheckAuthorizedUserRole()

{

                if (!HttpContext.Current.User.IsInRole(“Operator”))

      {

FormsAuthentication.SignOut();
/*Or else, you can redirect the user to the desired page.[Probably, Access Denied!]*/
      }            

}



Here system will check for the specific user role, if not found forms authentication will forces the user to signout.



This way you can have the custom implementation of role based authorization.

Popular posts from this blog

Debugging code running on Remote machine

Before performing below steps, you need to make sure you have pdb files matching dll version on the remote machine.  Open below folder in your remote machine C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\Remote Debugger\x64  Open that folder and launch as admin  msvsmon.exe  Select all options to allow firewall From Tools > Options  - Keep the settings to default (as shown below) and click ok.  At this point your remote debugger is all set. You need to connect from Visual Studio by entering Machine IP: Port (4022) 

Implement Serverside ViewState

If you think your website is running slowly and you need to improve performance by 150% in short time . This may help you a lot. ASP.NET ViewState is a great mechanism that simplifies the life of ASP.NET developers. But, as everybody knows, the .NET Framework saves the ViewState data as a hidden field on your ASPX page. If your page has only a few controls, this is not a problem. But, if your page has some Panel s and/or some DataGrid s, with the technique demonstrated on this article, you could reduce dramatically the load time of the page.

Web Functional Testing Automation using CasperJS and Nodejs

Background We are in era the of Web, Mobility and AI. Days are gone where we used to think Javascript is just for client side validation check before submitting web forms. Thanks to ECMAScript5 and above which advanced javascript language way forward. Many Enterprises across the world already building applications using lot of opensource Javascript technologies.  Automating the Testing of any web application is becoming challenging and critical for the business. Challenge is in terms of manage and maintain test hygiene throughout the application life cycle and overall product quality. The ideal behavior of any test automation is to be able to integrate as part of CI and CD  (Continuous Deployment)  build and be able to run without manual test run effort and publish test results with code coverage metrics. There are many different frameworks available in the market to solve automation problem. To name few:  CodedUI -  Browser based test automa...