Restrict unauthorized callers

From Guidance Share

Jump to: navigation, search

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

Your code should authorize users based on a role or identity before it connects to the database. Role checks are usually used in the business logic of your application, but if you do not have a clear distinction between business and data access logic, use principal permission demands on the methods that access the database.

The following attribute ensures that only users who are members of the Manager role can call the DisplayCustomerInfo method:

[PrincipalPermissionAttribute(SecurityAction.Demand, Role="Manager")]
public void DisplayCustomerInfo(int CustId)
{
}

If you need additional authorization granularity and need to perform role-based logic inside the data access method, use imperative principal permission demands or explicit role checks as shown in the following code fragment:

using System.Security;
using System.Security.Permissions;

public void DisplayCustomerInfo(int CustId)
{
 try
 {
   // Imperative principal permission role check to verify that the caller
   // is a manager
   PrincipalPermission principalPerm = new PrincipalPermission(
                                                  null, "Manager");
   // Code that follows is only executed if the caller is a member
   // of the "Manager" role
 }
 catch( SecurityException ex )
 {
  . . .
 }
}

The following code fragment uses an explicit, programmatic role check to ensure that the caller is a member of the Manager role:

public void DisplayCustomerInfo(int CustId)
{
 if(!Thread.CurrentPrincipal.IsInRole("Manager"))
 {
   . . .
 }
}

Note Additionally, if you are using ASP.NET 2.0 and you have enabled the Role Manager feature, you can use the Roles API to perform role checks. 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/default.asp?url=/library/en-us/dnpag2/html/PAGHT000013.asp

References

Personal tools