Get CAS IPermission for exception

If you’re working on a SharePoint solution that requires a custom code access security (CAS) policy, the following is an easy way of determining the permission(s) you need to add to the config.

For this to work, you need to be able to debug the code, which should be a given, considering you’re creating a custom CAS for a solution you’re writing . 🙂

A basic CAS will look something like:

<CodeAccessSecurity>
  <PolicyItem>
    <PermissionSet class="NamedPermissionSet" version="1">
      <IPermission class="SecurityPermission" version="1" Flags="Execution" />
      <IPermission class="AspNetHostingPermission" version="1" Level="Minimal" />
      <IPermission class="Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" version="1" ObjectModel="True" />
    </PermissionSet>
    <Assemblies>
      <Assembly Name="$SharePoint.Project.AssemblyName$" Version="$SharePoint.Project.AssemblyVersion$" PublicKeyBlob="$SharePoint.Project.AssemblyPublicKeyBlob$"/>
    </Assemblies>
  </PolicyItem>
</CodeAccessSecurity>


All the above does is effectively grant your custom assembly the ability to use the SharePoint object model.

Now, say you added code that performs some reflection, you would receive a security exception but may be left unclear exactly what permission policy is required for the CAS config. By debugging the code and setting a breakpoint on the catch block for the error:

public void GetListItem(SPList list)
try {
  SPContext context = SPContext.GetContext(Context, 0, list.ID, list.ParentWeb);
  SPListItem listItem = list.AddItem();
  var contextItem = (typeof(SPContext)).GetField("m_item", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  contextItem.SetValue(context, listItem);
 
  // Do other stuff
}
catch (SecurityException ex) {
  // do something with the exception
}

You will be able to get this information by typing the following into the Immediate window of Visual Studio (ctrl+i):

ex.m_demanded

m_demanded is a private field of the SecurityException class and can be drilled into from the Immediate window, QuickWatch, etc. while debugging.

The output can then be copied and pasted into your CAS config:

<IPermission class="ReflectionPermission" version="1" Unrestricted="true"/>

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve the maths problem shown below before posting: *

Follow

Get every new post delivered to your Inbox

Join other followers: