Saturday, April 4, 2015

Fix 401 Unauthorized error for anonymous users when use owssvr.dll

Library owssvr.dll is used for performing various operations against Sharepoint content: URL Protocol. E.g. you may retrieve data from particular list using this dll like this:[sites/][Site_Name/]_vti_bin/owssvr.dll?Cmd=Display&List=GUID&XMLDATA=TRUE

There is however problem with using owssvr.dll by anonymous users which may get HTTP 401 Unauthorized error. In order to make owssvr.dll work for anonymous users few things should be done. At first we need to enable anonymous state on particular SPWeb and add SPBasePermissions.ViewFormPages and SPBasePermissions.UseRemoteAPIs to Limited access role definition (SPRoleType.Guest) which is used for anonymous users:

   1: web.RoleDefinitions.BreakInheritance(true, true);
   2: var rd = web.RoleDefinitions.GetByType(SPRoleType.Guest);
   3: rd.BasePermissions |= SPBasePermissions.ViewFormPages |
   4:     SPBasePermissions.UseRemoteAPIs;
   5: rd.Update();
   6: web.AnonymousState = SPWeb.WebAnonymousState.On;
   7: web.Update();

This is however not enough. We also need to add SPBasePermissions.UseRemoteAPIs permission to the list from which we will retrieve data via owssvr.dll. The main problem is that when you enable anonymous access (grant read permissions for anonymous users) for the list from UI List Settings > List Permissions > Anonymous Access:


only the following permissions are added to SPList.AnonymousPermMask64:

SPBasePermissions.ViewListItems | SPBasePermissions.ViewVersions | SPBasePermissions.ViewFormPages | SPBasePermissions.Open | SPBasePermissions.ViewPages | SPBasePermissions.UseClientIntegration

and SPBasePermissions.UseRemoteAPIs is not there as you can see. Even if we added it on SPWeb level, without that anonymous users will still get 401 Unauthorized error when will try to use owssvr.dll library. So in order to make it work we need to do grant SPBasePermissions.UseRemoteAPIs on list level:

   1: SPList list = ...;
   2: list.BreakRoleInheritance(true);
   3: list.AnonymousPermMask64 = SPBasePermissions.ViewListItems |
   4:         SPBasePermissions.ViewVersions | SPBasePermissions.ViewFormPages |
   5:         SPBasePermissions.Open | SPBasePermissions.ViewPages |
   6:         SPBasePermissions.UseClientIntegration | SPBasePermissions.UseRemoteAPIs;
   7: list.Update();

After that owssvr.dll should work for anonymous users.

No comments:

Post a Comment