Using PowerShell to modify anonymous access permissions on SharePoint On-Premises

Anonymous access in SharePoint 2013

This post is about managing Anonymous Access on a SharePoint site (SPWeb) using PowerShell commandlets. It’s often a lot more feasible and even easier than using the browser interface! In some cases, it’s borderline impossible to avoid it anyway – since accessing the GUI switch might not be possible.

Description

Assume you have a site collection that’s you have published to the whole world. You’ll have anonymous access enabled at both web application and site collection -levels, and configured permissions at the root web -level. Now, let’s assume you want to disable anonymous access on a certain site deeper in the site structure. This way anonymous users could access your site at http://site.com and http://site.com/subsite, but not at http://site.com/subsite/deepsubsite. As an added bonus, you get security trimming! That means, that the web would even be removed from the navigation for any users, who cannot access it. Especially anonymous users!

Sounds pretty great. How to achieve this, though?

Continue reading

How to properly use SPWeb.AllowUnsafeUpdates?

SharePoint2013

At times you may need to allow unsafe updates to SPWeb objects to get your code to run. This, in SharePoint C# code-behind is done by setting SPWeb.AllowUnsafeUpdates to true. However, as this is an exception to security settings, and should generally not be done, it’s a good practice to limit the change to as small a scope as possible – even though the setting is only persisted for the duration of the request (unless the SPWeb object was gotten from SPSite.GetWeb() or SPSite.Webs[]).

What to do?

I’ve found the easiest way to temporarily allow unsafe updates in a safe way but without too much of extra code to be this:

using (SPWeb web = someWayToGetSPWebObject()) {

 bool allowUnsafeUpdate = web.AllowUnsafeUpdates;

 try {

  web.AllowUnsafeUpdates = true;

  // your unsafe code here

 }

 finally {

  web.AllowUnsafeUpdates = allowUnsafeUpdate;

 }

}

Please note, that it’s unwise to simply set the AllowUnsafeUpdates to false after the code, because there’s an ever-so-slight possibility of it screwing up some other code running in the same context at the same time! And of course, it’s likely to be unwise to allow unsafe updates if you’re handling data that was gotten as user input.