SharePoint Online - Update User Profile Properties Using CSOM App
I have a console application where I update the properties of a SharePoint Online user profile via CSOM. When I do it with the following code below (using username and password) it works fine.
private static void UpdateUserProfileProperties()
{
var userAccountName = "i:0#.f|membership|myAccounName@mySite.com";
var siteUrl = "https://mySite-admin.sharepoint.com";
var myUserName = "myUserName";
var myPassword = "myPassword";
var secureStringPassword = new SecureString();
myPassword.ToList().ForEach(c => secureStringPassword.AppendChar(c));
using (var context = new ClientContext(siteUrl))
{
var credentials = new SharePointOnlineCredentials(myUserName, secureStringPassword);
context.Credentials = credentials;
var peopleManager = new PeopleManager(context);
var personProperties = peopleManager.GetPropertiesFor(userAccountName);
context.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
context.ExecuteQuery();
}
}
I have now created an application in SharePoint (using the AppRegNew.aspx page). I have granted permissions at the app tenant level (via the AppInv.aspx page) and the following XML permission request:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl"/>
</AppPermissionRequests>
Now I am using clientID / clientSecret for authentication instead of username and password - using this code:
public static void UpdateUserProfileProperties2()
{
var userAccountName = "i:0#.f|membership|myAccounName@mySite.com";
var siteUrl = "https://mySite-admin.sharepoint.com";
var siteUri = new Uri(siteUrl);
var siteRealm = TokenHelper.GetRealmFromTargetUrl(siteUri);
var siteToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, siteRealm).AccessToken;
using (var context = TokenHelper.GetClientContextWithAccessToken(siteUri.ToString(), siteToken))
{
var peopleManager = new PeopleManager(context);
var personProperties = peopleManager.GetPropertiesFor(userAccountName);
context.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
context.ExecuteQuery();
}
}
I can get the token and context just fine. When the line is executed context.ExecuteQuery();
, I get the following exception:
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: Access is denied. You do not have permission to perform this action or access this resource.
The clientID / clientSecret of the application works for all kinds of other operations on the site. Is it possible to upload custom properties to admin site using clientID / clientSecret? If so, can you provide an example? How can I grant the application the appropriate permissions?
source to share