You might have came across a situation where you need to communicate with multiple site collection using CSOM but you don't want use any of below listed method:
- Authenticate using username and password (Service account).
- authenticate using client & secret (Need to trust application on every site collection prior to authenticate)
You don't want to use any of above, don't worry stay with me. Here is the alternative.
Azure Active Directory Application
The application has to be registered in Azure Active Directory and acts against SharePoint Online using an App Only access token, based on an X.509 self-signed Certificate.
Steps to implement:
Create the self signed certificate:
you have to create and configure a self-signed X.509 certificate, which will be used to authenticate your Application against Azure AD, while requesting the App Only access token. To create certificate use below command.
makecert -r -pe -n "CN=MyCompanyName MyAppName Cert" -b 1/25/2018 -e 1/25/2019 -ss my -len 2048
Azure Active Directory Application registration:
Open the Office 365 Admin Center (
https://portal.office.com) using the account of a user member of the Tenant Global Admins group.
Click on the "Azure AD" link that is available under the "Admin centers" group in the left-side tree view of the Office 365 Admin Center. In the new browser's tab that will be opened you will find the Microsoft Azure Management Portal. Once having access to the Azure Management Portal, select the "Active Directory" section, by clicking on the icon highlighted in the following screen shot:
You'll see on the left side of the blade that you opened the Azure AD tenant corresponding to your Office 365 tenant. Locate and select the option "App Registrations".
In the "App Registrations" tab you will find the list of Azure AD applications registered in your tenant. Click the "Add" button in the upper left part of the blade.
Then, provide a name for your application, select the option "Web app / API", and fill in the "Sign-on URL" (for console app you can use localhost). Make sure to use a forward slash at the end of the URL (otherwise you will get a 'reply address does not match error'). Click create when done.The newly created app registration will now be listed in your "App Registrations" list. Open it and then click into settings and then properties.
Copy the
Application ID value as you'll need it later.
Now, you should go back to the settings blade. Go into Keys where you'll create a Client Secret (used for app-only authentication). In order to do that, add a new security key (selecting 1 year, 2 years or never expires for key duration). Press the "Save" button in the lower part of the screen to generate the key value. After saving, you will see the key value. Copy it in a safe place, because you will not see it anymore.
Now click on "Required Permissions", and click on the "Add" button, a new blade will appear.
You need to configure the following permissions:
- Microsoft Graph (Delegated Permission)
- Read directory data
- Read all users' basic profiles
- Read and write access to user profile
- Windows Azure Active Directory (Delegated Permission)
- Sign in and read user profile
- Office 365 SharePoint Online (Application Permission)
- Read and write managed metadata
- Have full control of all site collection
For further details, see the following figure.
The "Application Permissions" are those granted to the application when running as App Only. The other set of permissions, called "Delegated Permissions", defines the permissions granted to the application when running under a specific user's account delegation (using an app and user access token, from an OAuth 2.0 perspective).
Click the Grant Permission button on the 'Required Permissions' tab, if you want to give non-tenant admin users access to the application.
Update Azure AD Application manifest
Start a PowerShell command window, and execute the following instructions:
$certPath = Read-Host "Enter certificate path (.cer)"
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$cert.Import($certPath)
$rawCert = $cert.GetRawCertData()
$base64Cert = [System.Convert]::ToBase64String($rawCert)
$rawCertHash = $cert.GetCertHash()
$base64CertHash = [System.Convert]::ToBase64String($rawCertHash)
$KeyId = [System.Guid]::NewGuid().ToString()
$keyCredentials =
'"keyCredentials": [
{
"customKeyIdentifier": "'+ $base64CertHash + '",
"keyId": "' + $KeyId + '",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": "' + $base64Cert + '"
}
],'
$keyCredentials
Write-Host "Certificate Thumbprint:" $cert.Thumbprint
Copy the output value into a text file as you will have to use it soon.
Go back to the Azure AD Application that you created in the previous step and click the "Manifest" button at the top of the blade, then click Edit'. This is how your screen should look like now:
Search for the keyCredentials property and replace it with the snippet you generated before, this will be similar to:
"keyCredentials": [
{
"customKeyIdentifier": "<$base64CertHash>",
"keyId": "<$KeyId>",
"type": "AsymmetricX509Cert",
"usage": "Verify",
"value": "<$base64Cert>"
}
],
Click Save when you complete this step.
Code:
Now open your CSOM application and use GetAzureADAppOnlyAuthenticatedContext method of PnP Core for creating context
OfficeDevPnP.Core.AuthenticationManager authManager = new OfficeDevPnP.Core.AuthenticationManager();
ClientContext context = authManager.GetAzureADAppOnlyAuthenticatedContext(siteUrl, Application Id, tenant Id, Certificate path, Certificate Password);
SiteUrl: Site Url
Application Id: Azure application Id which we created earlier.
Tenant Id: Office 365 tenant Id
Certificate Path: Certificate path which we created in step 1
Certificate Path: Password supplied while creating certificate
Your client context is ready enjoy the Code...!