I have a requirement to programmatically display a list of documents (which could be anywhere) on a SharePoint Server 2013 publishing site. The documents are found by using the KeywordQuery class from the Search API, driven by Managed Metadata matches.

I have been able to get the SPListItem and SPFile objects for the items concerned, but the issue I have now is how do I detect whether or not a user has access to these files? There is a requirement to "label" the protected documents as such.

This is simple enough if the user is logged in using SPListItem.DoesUserHavePermissions(SPBasePermissions.Open).

The issue I have is that I need to display every document which is available (including ones which require logging in). The site is extended to the internet Zone which has anonymous access enabled, so if a user is not logged in (anonymous), is there a way of easily detecting if they have access to a file?

SPListItem.DoesUserHavePermissions(SPBasePermissions.Open) does not seem to work in this case since I believe it relies on the SPUser object in the SPContext, which is null if you are not logged in.

Does anyone have any suggestions please?

有帮助吗?

解决方案 2

We have eventually found that the reason this wasn't working was because the code was running inside a SPSecurity.RunWithElevatedPrivileges block.

From what we've seen in debugging, DoesUserHavePermission will return true or false if a user is logged in, will return true if an anonymous user has permission, but throws an exception if an anonymous user does not have permission.

其他提示

We need to check the user login or anoymous access, then check the permission:

SPUser currentUser = SPContext.Current.Web.CurrentUser;
if( currentUser != null && !string.IsNullOrEmpty(currentUser.LoginName)
{
    bool permit = item.DoesUserHavePermissions(currentUser,SPBasePermissions.Open);
}
许可以下: CC-BY-SA归因
scroll top