In many instances we use ImportWebPart method of the WebpartManager class to import web parts in runtime. If you are using this method to render dynamic content in an anonymous internet facing site using SharePoint there are few points to be noted. Out of the box WebpartManager class expects certain permissions to successfully import a Web part in anonymous mode and the same has been implemented using Code Access Security. Permissions required will not be available in anonymous mode. Following article articulates a design to handle this. Keep reading….
What happens if you use out of the box WebPartManager Class?
Out of the box WebpartManager class works as expected in authenticated mode. If you have the site extended to anonymous mode you can notice that the pages hosting a web part or user control which dynamically hosts another web part instance using ImportWebPart Method will start challenging for credentials. First suspect for this might be to check whether you have published version of the page. After few hours of trouble shooting you may find that all pre-requisites are met and still the pages challenges for credentials. This is due to the fact that the out of box WebPartManager class expects certain permissions in runtime and the same is not available in anonymous mode. Next step is to run the code with Elevated privileges. This will not help the WebPartManager to get the needed permissions.
What’s going on in WebPartManager Class?
As per MSDN documentation WebPartManger class of SharePoint is designed to be used only in authenticated mode. But the design does not restrict us to extend the same based on our custom requirements. Important sections from the MSDN article.
What's the solution to use this in Anonymous mode?
To overcome the above mentioned limitation we need to create a custom WebPartManager with custom set of permissions. Below mentioned code snippet can be used directly to create the class. I have tested this in a big WCM site and the code has no bugs 🙂
Custom Web part Manager and Personalization class
Implementation or Usage Code
Happing coding 🙂