Skip to content

Granting access via Azure AD App‐Only with Certificate

Vadim Gremyachev edited this page Feb 24, 2024 · 3 revisions

Demonstrates how to authenticate SharePoint API via client certificate flow (Azure AD app-only)

Steps:

1. Registering the new application in Azure AD

Navigate to Microsoft Azure portal and register an Azure AD application in the Azure Active Directory tenant that is linked to your Office 365 tenant. Refer this documentation for a more details.

Once application has been created, collect Client Id

image

2. Configuring an X.509 Certificate for the application

To create a self signed certificate:

  • generate a private key: openssl genrsa -out private.key 2048
  • generate a public key: openssl req -new -x509 -key private.key -out publickey.cer -days 365
  1. upload the publickey.cer to your app in the Azure portal and note the displayed thumbprint for the certificate

image

3. Granting permissions to the application

Under API permissions in the left menu bar, click on the Add a permission button. Here you choose the permissions that you will grant to this application. Choose i.e.:

SharePoint
   Application permissions
     Sites
       `Sites.FullControl.All

Click on Add permissions button to add the permissions to your application. And finally, since Sites.FullControl.All application permission require admin consent in a tenant before it can be used, click Grant admin consent for {{organization name}} button and confirm the action by clicking on the "Yes" button that appears at the top.

image

4. Consuming certificate credentials with library

The example demonstrate how to initialize ClientContext instance and pass certificate credentials:

use Office365\SharePoint\ClientContext;

$siteUrl = "https://contoso.sharepoint.com";  //site or web absolute url 
$tenant = "contoso.onmicrosoft.com"; //tenant id or name
$thumbprint = "--thumbprint goes here--";
$clientId = "--client app id goes here--";
$privateKetPath = "-- path to private.key file--"
$privateKey = file_get_contents($privateKetPath);

$ctx = (new ClientContext($siteUrl))->withClientCertificate(
    $tenant, $clientId, $privateKey, $thumbprint);

$whoami = $ctx->getWeb()->getCurrentUser()->get()->executeQuery();
print $whoami->getLoginName();

References