Code Access Security policy template for Visual Studio 2010 SharePoint Developer Tools

, , , ,

SharePoint 2010 ships with the Sandbox: a new concept that allows you to deploy solutions with limited trust. Still there are many scenarios to think of when you might need to deploy your work to the Web Application’s BIN directory. When doing that, you need to define for your assembly a CAS policy, which specifies what your code should and should not be allowed to do. While the contents of the policy always depend on your code, I have noticed that there are a few entries that are common for almost every solution deployed to the BIN directory.

Adding a new CAS policy to your SharePoint Solution is extremely easy when working with the new Visual Studio 2010 SharePoint Developer Tools. All you have to do is to open the Package Designer (1), choose Manifest from the sections at the bottom (2) and open the Edit Options section (3).

Editing the CAS policy contens with the Package Designer

The next step is to insert the contents of your CAS policy.

<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>

The above policy contains the minimal set of permissions plus it allows your code to use the SharePoint Object Model. Although it looks like an ordinary CAS policy, notice the tokens in the Assembly entry. These tokens will be replaced by the Visual Studio 2010 SharePoint Developer Tools during the packaging process by the real values.

The above template contains the most common entries and is a good starting point when working with SharePoint Solutions deployed to the Web Application’s BIN directory. Depending on your code you might need to add additional SharePoint permissions or some other permissions as required by your code.


Possibly related posts

28 Responses to “Code Access Security policy template for Visual Studio 2010 SharePoint Developer Tools”

  1. Tweets die vermelden Code Access Security policy template for Visual Studio 2010 SharePoint Developer Tools - Waldek Mastykarz -- Topsy.com Says:

    [...] Dit blogartikel was vermeld op Twitter door Waldek Mastykarz, Saed Shela. Saed Shela heeft gezegd: "Code Access Security policy template for Visual Studio 2010 SharePoint Developer Tools" http://bit.ly/cP02Bg #Sp2010 #VS2010 #CAS [...]

  2. Eugene Rosenfeld Says:

    Of course, the trick is figuring out just which CAS policies your solution's assemblies need.

  3. Waldek Mastykarz Says:

    @Eugene: exactly. Somehow I find using Reflector for that purpose just great. Wish there was an easier approach though.

  4. Bas Lijten Says:

    Waldek,

    First of all, I think that the permissionset is quite helpful, if you really want to have bin-deployment. We decided that, when possible, we want every dll to be deployed to the bin, for our own reasons (when possible!)

    But at the moment, we have a mossrap at our (Enterprise)company. For every trustlevel that is not minimal, Microsoft says it`s a potential security issue.

    Is this still the way in SP2010?

  5. Waldek Mastykarz Says:

    @Bas: that's the whole trick with CAS, isn't it: to allow code to do more than default? I think every time you open something introduces a possible threat: no matter if it's SharePoint or just an ordinary ASP.NET app.

  6. Peter Says:

    Hi Waldek Mastykarz,
    I have an issue when i insert CAS into my webpart:"Error occurred in deployment step 'Add Solution': Property set method not found."
    Do you know what problem i have? and how to solve it?
    Thanks,
    Peter

  7. Waldek Mastykarz Says:

    @Peter: yes, it's a known issue. See http://blog.mastykarz.nl/error-deploying-wsp-cas-visual-studio-2010-sharepoint-developer-tools-fix/ for more information and solution.

  8. Peter Says:

    yeah, thanks Waldek so much. I solved my problem.
    Peter.

  9. Neagu Catalin Says:

    Hi Waldek,
    I have a question that is somehow related with CAS Policies. It's possible to activate a feature (site or web scope) with an atached feature event receiver, from powershell, using, enable-feature cmd, for a solution deployed to a webapplication. I tried everything that I found on google to resolve this issue. The error is : "Enable-SPFeature : Failed to load receiver assembly "…..: System.IO.FileNotFoundException: Could not load file or assembly '….' or one of its dependencies. The system cannot find the file specified.". The same question for upgrade-spfeature cmd. What I want to mention here is the fact that this feature can be activated without any problems from SP UI and also the solution manifest file have inside CAS policies and the error it's not related with any line of code written in feature event receivers.. Without these CAS Polciies even the deploy process will fail.For me it's very important to activate this feature from powershell automatically on all the site collections on ten webapplications in different farms (a nightmare from SP UI)and it seems impossible to do this in the above scenario. Let me reformulate the question: it's a Microsoft bug in SP2010, it's not possible to achieve this (EventReceiver-Feature-WepApp-powershell-enable-spfeature) or what CAS Policies i need for enable the feature from powershell?

  10. Neagu Catalin Says:

    The issue can be tested very easy: using empty sharepoint project template, add a new feature, add a event receiver to the feature, change the assembly deployment target to webapplication, add CAS policies, build, package and from powershell: add-spsolution, install-spsolution, and finally try to execute enable-spfeature….

  11. Waldek Mastykarz Says:

    @Neagu: In my understanding an assembly with a Feature Receiver must always be deployed to GAC. This has to do with the fact that you can activate a Feature in many ways other than through the Web UI, where the web context it not available and therefore the assembly cannot be loaded (found). By deploying the assembly to GAC and providing its fully qualified name you make it possible to all other processes than the w3wp.exe to load the receiver assembly.

  12. Neagu Catalin Says:

    Hi Waldek,
    Thank you very much for your fast answer…

  13. EXAM PREP « Kollipara's space Says:

    [...] Waldek Mastykarz’s article on CAS: http://blog.mastykarz.nl/code-access-security-policy-template-visual-studio-2010-sharepoint-develope... [...]

  14. Jos van Putte Says:

    This was very useful ! I try to migrate my visual webparts from the GAC to BIN and ran into this problem. The next problem is that my ascx page is no longer visible when deploying as a webapplication. Has anyone found a solution for this as well ?

  15. Waldek Mastykarz Says:

    @Jos: I would definitely suggest you used Visual Web Part (Sandboxed) instead even if you're not deploying to Sandbox. Because the ASCX is being compiled it's faster and it requires less permissions.
    In your case: are you getting any exceptions? Have you tried debugging the code to get some more information about what's causing the error?

  16. Jos van Putte Says:

    @Waldek: I cannot deploy to a sandbox as I get the error 'The deployment type "TemplateFile" of file ..ascx in Project Item .. is not compatible with a Feature in a Sandboxed Solution.

    What I did is take the project, set the Deployment target to WebApplication and copied your security code in the package manifest.
    When I deploy is it gives me the message :
    [HttpException (0x80004005): The file '/_CONTROLTEMPLATES/Waarderingsscherm/Waarderingsscherm/Waarderingsscherm.ascx' does not exist.]
    System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) +11096274
    System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +163
    System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +116
    System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath) +69
    Waarderingsscherm.WaarderingsWebPart.WaarderingsWebPart.CreateChildControls() +179
    System.Web.UI.Control.EnsureChildControls() +146
    System.Web.UI.Control.PreRenderRecursiveInternal() +61
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394

  17. Jos van Putte Says:

    @Waldek: I cannot deploy to a sandbox as I get the error \'The deployment type \"TemplateFile\" of file ..ascx in Project Item .. is not compatible with a Feature in a Sandboxed Solution.

    What I did is take the project, set the Deployment target to WebApplication and copied your security code in the package manifest.
    When I deploy is it gives me the message :
    [HttpException (0x80004005): The file \'/_CONTROLTEMPLATES/Waarderingsscherm/Waarderingsscherm/Waarderingsscherm.ascx\' does not exist.]
    System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) +11096274
    System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +163
    System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +116
    System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath) +69
    Waarderingsscherm.WaarderingsWebPart.WaarderingsWebPart.CreateChildControls() +179
    System.Web.UI.Control.EnsureChildControls() +146
    System.Web.UI.Control.PreRenderRecursiveInternal() +61
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394

  18. Jos van Putte Says:

    @Waldek: I cannot deploy to a sandbox as I get the error \\\'The deployment type \\&quot;TemplateFile\\&quot; of file ..ascx in Project Item .. is not compatible with a Feature in a Sandboxed Solution.

    What I did is take the project, set the Deployment target to WebApplication and copied your security code in the package manifest.
    When I deploy is it gives me the message :
    [HttpException (0x80004005): The file \\\'/_CONTROLTEMPLATES/Waarderingsscherm/Waarderingsscherm/Waarderingsscherm.ascx\\\' does not exist.]
    System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) +11096274
    System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +163
    System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile) +116
    System.Web.UI.TemplateControl.LoadControl(VirtualPath virtualPath) +69
    Waarderingsscherm.WaarderingsWebPart.WaarderingsWebPart.CreateChildControls() +179
    System.Web.UI.Control.EnsureChildControls() +146
    System.Web.UI.Control.PreRenderRecursiveInternal() +61
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Control.PreRenderRecursiveInternal() +224
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3394

  19. Waldek Mastykarz Says:

    @Jos: As the error says, you cannot deploy ASCX to CONTROLTEMPLATES in a Sandboxed Solution. Instead, you should be using the Visual Web Part Sandboxed that ships with the Visual Studio 2010 SharePoint Power Tools.

  20. Jos van Putte Says:

    Thank you. I thought it was a security problem..
    (Sorry for the duplicate messages)

    I found the power tools and installed them but it is still not possible to create a sandboxed visual web part project.

  21. Waldek Mastykarz Says:

    @Jos: Did you install Visual Studio 2010 SharePoint Power Tools? There are other Power Tools as well so you have to check the ones you've got are the ones for SharePoint.

  22. Jos van Putte Says:

    @Waldek: I found it.. I started a new solution (empty) and added a new item to it from the solution explorer. There were the new items from the power tools..
    Thnaks for your help.

  23. Waldek Mastykarz Says:

    @Jos: great to hear it's working. You're welcome :)

  24. Oliver Says:

    Hi Waldek,

    I read your blog post about how to add CAS policies to a sharepoint 2010 solution with Visual Studio 2010. Really very informative :-)

    At the moment I'm working on a little sharepoint 2010 webpart where I added a methode that uses RunWithElevatedPrivileges.
    I need to add CAS policies to that webpart project – so I added the policies I copied from your post.
    That worked fine until my code calls the method with RunElevatedPrivileges. In that case a security exception is thrown telling me that there is something wrong with aquiring policies from .
    But I already added this to my CAS policies (like you've done).
    I'm really stuck now – what policy do I need to added when using RunWithElevatedPrivileges?
    Although I'm not a newbie to sharepoint development – I'm a newbie to using CAS. So I really would appreciate to get some help from you.

    Regards,
    Oliver

  25. Waldek Mastykarz Says:

    @Oliver: The CAS policy that I provided is basically a starting point. Depending on what you're doing you might need to extended it with additional permissions, and elevating privileges is an example of this. When calling RunWithElevatedPrivileges in your code you need to add the Impersonate attribute (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.security.sharepointpermissionattribute.impersonate.aspx) to your SharePoint Permission in CAS (Impersonate="true"). With that everything should work okay.

  26. Vasu K Says:

    We created a custom workflow and associated it with a document library. This works fine when I make "Trust Level" to "Full" in the web.config file. We kept "Trust Level" to "WSS_Minimal" in web.config file and created a "Code Security Access (CAS)" policy and added to the workflow project's "Package Manifest" as described in this post.

    We are getting "Failed to Start (retrying)" error now and workflow is not starting.

    Here is the CodeAccessSecurity that we used:

    Can you please let us know if we need to make changes to the above CAS policy to make the workflow work?

  27. Alex Says:

    I've got an assembly that workd perfectly well if I set my app trust level to "Full" but I don't want to do that, I'd prefer setting only my assembly's trust to full, is that possible? the problem I have is that this assembly call webservice, any url could be entered. I tried adding this to my package.template.xml file but it didn't work :

  28. Waldek Mastykarz Says:

    @Alex: You should be able by adding a custom CAS policy to your Package and configuring permissions for the WebService. This article might help you find out which permissions your assembly requires exactly: http://blog.mastykarz.nl/working-easier-custom-cas-policies/.

Leave a Reply

Security Code:

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS
Copyright © 2007 - 2012 Waldek Mastykarz

Creative Commons License