Asserting Permissions

We will now extend the light detector sample to add an auditing facility, so that whenever LightController.Read() is called, an entry is made in a text file, C:\LightReadAudit.txt, recording the fact that this method is called. This will illustrate the use of asserting a permission that would otherwise be denied to calling code.

The AuditingLightDetector Sample

The code for the AuditingLightDetector sample is identical to that for the LightDetector sample, except for the following additions to LightController.ReadValue():

 public class LightController {    public Color ReadValue()    {       // Make auditing entries       string auditFilePath = @"C:\LightReadAudit.txt";       FileIOPermission ioperm = new FileIOPermission(                                          PermissionState.Unrestricted);       ioperm.Assert();       StreamWriter sw = new StreamWriter(auditFilePath, true);       sw.WriteLine("ReadValue() called at " + DateTime.Now.ToString());       sw.WriteLine("   from assembly at " +                    Assembly.GetEntryAssembly().CodeBase);       sw.WriteLine("    " + Assembly.GetEntryAssembly().FullName); sw.WriteLine();       sw.Close();       CodeAccessPermission.RevertAssert();       LightDetectorPermission perm = new LightDetectorPermission(                                              LightDetectorPermissions.Read);       perm.Demand();       return Color.FromArgb(255, 40, 30);    } } 

The point is that writing to the auditing file using the System.IO classes requires FileIO permission to access and append to the new file. If we just attempt the file append without asserting the permission first, then the code will fail because the stack walk will reveal that the calling assembly, LightDetector.exe, doesn't have permission to do this. By asserting this permission first, we guarantee that our assembly will still be able to perform the auditing operation. This provides an example of how calling CodeAccessPermission.Assert() can allow trusted code to perform operations on behalf of less trusted code, which are known to be safe but require permissions that would not have been granted to this less trusted calling code.

Running LightDetector.exe once on the local machine, and then once from the trusted Internet site caused the following to be placed in the auditing file:

 ReadValue() called at 02/11/2002 22:08:09    from assembly at file:///E:/IL/LightDetector.exe    LightDetector, Version=1.0.1.0, Culture=neutral, PublicKeyToken=22a8cada780967db ReadValue() called at 02/11/2002 22:09:42    from assembly at http://www.simonrobinson.com/test/lightdetector.exe    LightDetector, Version=1.0.1.0, Culture=neutral,                                            PublicKeyToken=22a8cada780967db 



Advanced  .NET Programming
Advanced .NET Programming
ISBN: 1861006292
EAN: 2147483647
Year: 2002
Pages: 124

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net