Checking authorization through roles
In ASP.NET application or any application, is common to verify if the user has permission for a resource, like page, button, command, etc. In last days, I received an e-mail where a guy had performance problems.
In his page, there is a delete button in each line of GridView control. So, in RowDataBound event, he checks if the current user is in a specific role or not. But the problem is that he calls the IsUserInRole method for each line/record. In hundreds of lines/records in GridView, this method will always be called and, for each call, all code in this method will be performed. The example is showed below:
[ The old RowDataBound event ]
if(e.Row.RowType == DataControlRowType.DataRow) {
e.Row.FindControl(“btnDelete”).Visible = Roles.IsUserInRole(“Administrator”);
}
[ The new RowDataBound event ]
private bool _isInAdministratorRole;
//….
this._isInAdministratorRole = Roles.IsUserInRole(“Administrator”);
//….
if(e.Row.RowType == DataControlRowType.DataRow) {
e.Row.FindControl(“btnDelete”).Visible = this._isInAdministratorRole;
}
Small techniques like this can improve the application performance. “Caching code” is explained in Code Complete Book - Second Edition, at Chapter 26, pages 628 and 629.
There are other techniques related with roles in ASP.NET WebApplication. These techniques allow role caching in client cookies through cacheRolesInCookie attribute. It prevents in each request, to make a new query in database (or other repository), to find specific roles for current logged user and attach in HttpContext object.
Caching roles in client-side cookies can improve the performance if your application has a slow data access or a large number of roles. But this technique has security problems and you need to be careful:
- Persistent authorization cookies will be stored in a user's profile and can be stolen if an attacker gets physical access to the machine. This will also help prevent problems for users who access your application from public or shared machines and forget to log out.
- Sending cookies out exclusively over SSL makes it much harder for an attacker to sniff the cookie values off the wire. If an attacker can get a copy of an authorization cookie, they can potentially emulate that role, allowing them to elevate their privilege in the system.
If caching of roles in client-side is necessary, so enable the cookieRequireSSL attribute in roleManager element for security reasons. But, SSL requires a certificate (if you don’t have, it’s necessary to buy it) and performance can be harmed. It’s very important to analyze the scenario and adopt the better strategy.