Last active
February 24, 2025 13:15
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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