How to Make an O365 SharePoint Online site collection read-only and inaccessible

Introduction 
 
This blog talks about how a site collection in O365 can be made read-only or inaccessible. It also discusses how when the site collection is inaccessible, you can redirect the users to an information page.
 
Problem Statement 
 
We were recently working on a project in which we needed to do a tenant-to-tenant migration. As a part of the migration process, we wanted to make the source site collection ready after the migration and then after 2 weeks' time, make it inaccessible. When the site collection was inaccessible, we also wanted to redirect the user to a page that would have an explanation of why they were unable to access the site.
 
Solution 
 
The ability to make a site read-only or inaccessible is provided by the lockstate property of the Set-SPOSite powershell command.
 
Read Only 
 
In order to make a site read-only, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState ReadOnly
 
Inaccessible 
 
In order to make a site inaccessible, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState NoAccess
 
When the site is set to NoAccess, the business users will be shown a standard 403 forbidden page.
 
Redirection 
 
To make this user-friendly, there may be a need to inform the business users as to why they are unable to open the site.
 
This can be achieved by including the parameter  "NoAccessRedirectUrl" along with the URL in the PS command.
 
Set-SPOTenant -NoAccessRedirectUrl 'https://www.contoso.com'
 
Note: As this URL is set at the Tenant level, every SPO site and ODFB site that has been marked as NoAccess will be redirected to the 1 above URL, hence the URL to which the users are redirected should contain information addressing both of them.
 
Unlock 
 
In order to make a site accessible and editable by end-users, we have to execute the command:
 
Set-SPOSite https://[tenant].sharepoint.com/sites/targetsite -LockState Unlock
 
CSOM
 
While we have seen the powershell commands, this can also be executed through CSOM 
  1. using (var clientContext = new ClientContext(tenantUrl))  
  2. {  
  3.       clientContext.Credentials = spoCredentials;  
  4.       var tenant = new Tenant(clientContext);  
  5.       var siteProperties = tenant.GetSitePropertiesByUrl(siteUrl, true);  
  6.       clientContext.Load(siteProperties);  
  7.       clientContext.ExecuteQuery();  
  8.       Console.WriteLine("LockState: {0}", siteProperties.LockState);  
  9.       siteProperties.LockState = "Unlock";  
  10.       siteProperties.Update();  
  11.       clientContext.ExecuteQuery();  
  12. }
Reference links