Specifying Security the right way in a web part

Posted Monday, June 25, 2007 1:35 PM by C-Dog's .NET Tip of the Day

So you went through the hassel of creating a new web part and you have written something fairly elaboration that actually makes use of the WSS Object Model only to find that you get a message such as the following:

Request for the permission of type 'Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' failed..

Although there is a wealth of samples out there on how to build web parts few I have found actually show you how to install them correctly. There are basically three ways to correct this issue, one of them being the cowboy way. One a sort of ok solution and the last one is the correct way. If you are curious the Cowboy way is to install the DLL of your web part into the GAC. This gives the DLL full trust which is obviously not the way you want to do it. The other way to do it is to create a custom security policy and explicitly give the needed permissions to your assembly in that policy.

However, the last way is the correct way. Looking at the error, you should be able to deduce that this is a result of Code Access Security (CAS). That means it is actually easy to fix. You just need to know what permission to demand. The SharePointPermissionAttribute is what you need. If you need access to the object model, specify ObjectModel = true. There are also a few other permissions you can demand with this but they are not as common. A typical CAS attribute for use with SharePoint would look like this above your class declaration.

[SharePointPermissionAttribute(SecurityAction.Demand, ObjectModel = true)]

Hopefully this helps those out there that need it. I found very little information out there that gave me the exact attribute to add.

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=367