Elevate User Access with App Only Policy
The reason we use RunWithElevatedPrivilages is to execute our code with elevated permission regardless of current login user permission.
By default, SharePoint Apps run in context of user + app which means current user and the app both should have sufficient rights to access SharePoint resources. But in some cases we need our app to access SharePoint resources regardless of current user permission, this is where AppOnlyPermssion comes into picture. In this article I will let you know how to use it.
Solution
To make an App performing work that the user does not have permission to means we will use the app only policy. To enable the App Only policy in your app, you have to add the "AllowAppOnlyPolicy" attribute to your "AppPermissions" element in the App Manifest:
- <AppPermissionRequests AllowAppOnlyPolicy="true">
- </AppPermissionRequests>
S2S (High Trust) - App Only Context
An S2S access token by calling the GetS2SAccessTokenWithWindowsIdentity method of the TokenHelper class. Use the TokenHelper::GetS2SAccessTokenWithWindowsIdentity method, passing a null for the WindowsIdentity parameter.
Let’s see how we can actually utilize the App Only policy to elevate user permissions. I have written the following code in the code behind of the TestPage.aspx of S2S Provider Hosted App.
Code:
- Uri _hostWeb = new Uri(Request.QueryString["SPHostUrl"]);
- string appOnlyAccessToken = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(_hostWeb, null);
- using(ClientContext clientContext = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(_hostWeb.ToString(), appOnlyAccessToken))
- {
- List Testlist = clientContext.Web.Lists.GetByTitle("TestList");
- ListItemCreationInformation info = new ListItemCreationInformation();
- Microsoft.SharePoint.Client.ListItem item = Testlist.AddItem(info);
- item["Title"] = "Created S2SApp";
- item["Body"] = "Created from S2S” + DateTime.Now.ToLongTimeString();
- item.Update();
- clientContext.Load(item);
- clientContext.ExecuteQuery();
- }
Note:
As you can see, the ClientContext that is opened with the appOnlyAccessToken will run with the identity of the SHAREPOINT\App account. This is a very good practice to remember even when using RunWithElevatedPreviledges in the Server Object Model.
References:
"SharePoint 2013 App Only Policy Made Easy"
No comments:
Post a Comment