Previous Tip  |  Next Tip  |  Index (recent)   |  Design Tips   | [Bill's Home]

244. Role-based security

The Microsoft .NET environment now offers an excellent alternative to Java in producing portable and secure code. It uses a role-based approach for user authentication, with the WindowsIndentity class, where the GetCurrent() method can be used to get the current user. The WindowsPrincipal class can then be used to apply the role. For example, to test if the user is an administrator: [Click here to download the EXE][Click here to download of the solution]

using System; 
using System.Security; 
using System.Security.Principal;
namespace ConsoleApplication3
{
class Class1
{
static void Main (string[] args) { WindowsIdentity myID = WindowsIdentity.GetCurrent(); System.Console.WriteLine("Your ID: " + myID.Name); System.Console.WriteLine("Authentication: " +myID.AuthenticationType); WindowsPrincipal myPrin = new WindowsPrincipal(myID); if (myPrin.IsInRole(WindowsBuiltInRole.Administrator)) System.Console.WriteLine("You're an Administrator "); else System.Console.WriteLine("You're not an Administrator"); Console.ReadLine(); } } }

A sample run gives:

Your ID: FREDS\Fred
Authentication: NTLM
You're an Administrator

Other roles are also defined, such as:

WindowsBuiltInRole.Guest
WindowsBuiltInRole.PowerUser
WindowsBuiltInRole.User

Next we could apply this security to only allow an administrator to view the IP address of the computer, with: [Click here to download the EXE][Click here to download of the solution]

using System;
using System.Security;
using System.Security.Principal;
using System.Net;
namespace ConsoleApplication3
{
 class Class1
 {
 static void Main (string[] args)
 {
  WindowsIdentity myID = WindowsIdentity.GetCurrent();
  System.Console.WriteLine("Your ID: " + myID.Name);
  System.Console.WriteLine("Authentication: " + myID.AuthenticationType); 
  WindowsPrincipal myPrin = new WindowsPrincipal(myID); 
  if (myPrin.IsInRole(WindowsBuiltInRole.Administrator))
  {
   string strHostName = Dns.GetHostName();
   IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
   IPAddress [] addr = ipEntry.AddressList;
   System.Console.WriteLine("IP: " + addr[0]);
  }
  else
   System.Console.WriteLine("Sorry ... you have no permissions for this");
 }
 }
} 

A sample run gives:

Your ID: FREDS\Fred
Authentication: NTLM
IP: 192.168.0.4

Thus, applications can be designed so that they have integrated security for certain privileges, each of which can be defined by the machine which is actually running the program. Thus, if a user uses an application which changes the system registry, the program can detect if the user is a system administrator, and only make the change if they are.