Reputation: 3
I would like to find a way to set the LockState property of SharePoint Online sites programmatically in C# - either to ReadOnly or Unlock as it is necessary.
I have tried to use PnP Framework with something like this:
using (var cc = new AuthenticationManager()
.GetACSAppOnlyContext(siteUrl, clientId, clientSecret))
{
var tenant = new Tenant(cc);
var siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, true);
tenant.Context.Load(siteProperties);
await tenant.Context.ExecuteQueryAsync();
siteProperties.LockState = readOnly ? "ReadOnly" : "Unlock";
siteProperties.Update();
await tenant.Context.ExecuteQueryAsync();
}
Here the siteUrl is like https://<domain>-admin.sharepoint.com/sites/{site key}
When I run this I am getting a "Token request failed" error when trying to load the site properties.
Is this due to permissions on the App Registration which is being used to authenticate here? What permissions need to be set up to allow updates to the LockState on a SharePoint site via TenantAdministration?
Otherwise, is it possible to do this via Graph API / GraphServiceClient instead of using PnP Framework?
Any help or a point in the right direction would be appreciated. Thanks!
Upvotes: 0
Views: 239
Reputation: 409
On SharePoint On-Premise systems setting a site collection to read-only mode was easy. Administrators could activate the read-only state in the central administration or they could write PowerShell or C# Code. SharePoint Online does not offer any of these methods anymore.
You can set a site collection read only using a site policies and CSOM.
public void SetReadOnlyState(string siteUrl, bool readOnly, ClientContext centralAdminContext)
{
var tenant = new Tenant(centralAdminContext);
var siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, true);
tenant.Context.Load(siteProperties);
tenant.Context.ExecuteQuery();
if (readOnly)
{
siteProperties.LockState = "ReadOnly";
}
else
{
siteProperties.LockState = "Unlock";
}
siteProperties.Update();
tenant.Context.ExecuteQuery();
}
Upvotes: 0
Reputation: 549
Very first do not use ACS App only context and its retired (but not end of life!).
This is a permission issue due to wrong application permissions granted during the app registration. You are providing app access to the Tenant level and hence the app should be registered in the admin center appregnew.aspx page. PFB check sheet for permission xml
SharePoint ACS APP permission check sheet
Upvotes: 0