Skip to content

Instantly share code, notes, and snippets.

@Yvand
Last active February 24, 2025 13:15
Show Gist options
  • Save Yvand/9e2f4962dfea4461526e49d84b3ccf20 to your computer and use it in GitHub Desktop.
Save Yvand/9e2f4962dfea4461526e49d84b3ccf20 to your computer and use it in GitHub Desktop.
Get Azure AD app-only access token for SPO scope using certificate authentication
# loads "Microsoft.Identity.Client.dll" from module "PnP.PowerShell"
$moduleName = "PnP.PowerShell"
$module = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
if ($null -ne $module) {
$modulePath = $module.InstalledLocation
} else {
$module = Get-Module -ListAvailable -Name $moduleName
if ($null -eq $module) {
Write-Host -ForegroundColor Red "Module '$moduleName' was not found, install it by running 'Install-Module -Name $moduleName'"; return;
}
$modulePath = (Get-Item $module.Path).DirectoryName
}
$identityClientDll = Join-Path -Path $modulePath -ChildPath "Core\Microsoft.Identity.Client.dll"
Add-Type -LiteralPath $identityClientDll
# Add-Type -LiteralPath "$($env:LOCALAPPDATA)\PowerShell\Modules\Microsoft.Graph.Authentication\2.24.0\Dependencies\Desktop\Microsoft.Identity.Client.dll"
# Add-Type -LiteralPath "$($env:LOCALAPPDATA)\PowerShell\Modules\Microsoft.Graph.Authentication\2.24.0\Dependencies\Microsoft.IdentityModel.Abstractions.dll"
# Variables to edit
$tenantId = "tenantId"
$clientId = "clientId"
$tenantPrefix = "tenantPrefix"
$certificatePfxFullPath = "certificatePfxFullPath.pfx"
$certificatePfxPassword = "certificatePfxPassword"
# Init
[string[]] $scopes = @("https://$tenantPrefix.sharepoint.com/.default")
$passwordParameter = New-Object -TypeName HashTable
if ($false -eq [string]::IsNullOrWhiteSpace($certificatePfxPassword)) {
$securePassword = ConvertTo-SecureString -String $certificatePfxPassword -Force -AsPlainText
$passwordParameter.Password = $securePassword
}
$certificate = Get-PfxCertificate -FilePath $certificatePfxFullPath @passwordParameter
# Gets the access token using MSAL Microsoft.Identity.Client.dll https://www.powershellgallery.com/packages/Microsoft.Identity.Client/
# Doc: https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client?view=msal-dotnet-latest
$confidentialClientApplicationBuilder = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($clientId).WithCertificate($certificate).WithTenantId($tenantId)
$confidentialClientApplication = $confidentialClientApplicationBuilder.Build()
$token = $confidentialClientApplication.AcquireTokenForClient($scopes).ExecuteAsync().GetAwaiter().GetResult()
$token.AccessToken
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment