Use explicit role checks for fine-grained authorization

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

Declarative security checks prevent a user from accessing a class or calling a specific method. If you need additional logic inside a method to make authorization decisions, either use imperative principal permission demands or explicit role checks using IPrincipal.IsInRole. These approaches allow you to use additional runtime variables to fine tune the authorization decision. The following example shows the use of an imperative principal permission demand:

// Imperative syntax
public void SomeRestrictedMethod()
{
 // Only callers that are members of the specified Windows group
 // are allowed access
 PrincipalPermission permCheck = new PrincipalPermission(
                                        null, @"DomainName\WindowsGroup");
 permCheck.Demand();
 // Some restricted operations (omitted)
}

The following example shows the use of IPrincipal.IsInRole:

public void TransferMoney( string fromAccount,
                          string toAccount, double amount)
{
 // Extract the authenticated user from the current HTTP context.
 // The User variable is equivalent to HttpContext.Current.User if you 
 // are using an .aspx page (or .asmx)
 WindowsPrincipal authenticatedUser = User as WindowsPrincipal;
 if (null != authenticatedUser)
 {
   // Note:  To retrieve the authenticated user's username, use the 
   // following line of code
   // string username = authenticatedUser.Identity.Name;
   // If the amount exceeds a threshold value, manager approval is required
   if (amount > thresholdValue) {
     // Perform a role check
     if (authenticatedUser.IsInRole(@"DomainName\Manager") )
     {
       // OK to proceed with transfer
     }
     else
     {
        throw new Exception("Unauthorized funds transfer");
     }
   }
   else
   {
     . . .
   }
 }
}

You may also have a method that allows callers from several different roles. However, you might want to subsequently call a different method, which is not possible with declarative security.

Note If you are running ASP.NET 2.0, you can use the Role Manager feature for fine-grained authorization. For more information on using the Role Manager feature in ASP.NET 2.0, see "How To: Use Role Manager in ASP.NET 2.0." at http://msdn.microsoft.com/library/en-us/dnpag2/html/PAGHT000013.asp

References

Personal tools