Skip to content

Granting access via Azure AD App‐Only with Certificate

Vadim Gremyachev edited this page Sep 29, 2023 · 3 revisions

Demonstrates how to authenticate SharePoint API via client certificate flow

Steps:

  1. generate Self-Signed SSL 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
  2. upload the publickey.cer to your app in the Azure portal
  3. note the displayed thumbprint for the certificate
  4. initialize ClientContext instance and pass thumbprint and the contents of private.key along with tenantName and clientId into withClientCertificate method as demonstrated below

Example

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