Skip to content

Instantly share code, notes, and snippets.

Created January 25, 2015 22:40
What would you like to do?
Obtain the access token from a Microsoft Azure Access Control Service (ACS) account that is associated with the customer's Microsoft Office 365 tenancy
Obtain an app-only access token from ACS.
Retrieves an app-only access token from ACS to call the specified principal
at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
null, the "Realm" setting in web.config will be used instead
Get-SPOAccessToken -Url "" -ClientId "" -ClientSecret ""
Function Get-SPOAccessToken([string]$ClientId,[string]$ClientSecret,[Uri]$WebUri){
$SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"
$realm = GetRealmFromTargetUrl -TargetApplicationUri $WebUri
$accessToken = GetAppOnlyAccessToken -ClientId $ClientId -ClientSecret $ClientSecret -TargetPrincipalName $SharePointPrincipal -TargetHost $WebUri.Authority -TargetRealm $realm
return $accessToken.access_token
function GetRealmFromTargetUrl([Uri]$TargetApplicationUri)
$url = $WebUrl + "/_vti_bin/client.svc"
$headers = @{}
try {
$response = Invoke-WebRequest -Uri $TargetApplicationUri -Headers $headers -Method Get
catch [Net.WebException] {
$authResponseHeader = $_.Exception.Response.Headers["WWW-Authenticate"]
#$bearerKey = "Bearer realm="
$bearer = $authResponseHeader.Split(",")[0]
$targetRealm = $bearer.Split("=")[1]
return $targetRealm.Substring(1,$targetRealm.Length-2)
return $null
Function GetAppOnlyAccessToken([string]$ClientId,[string]$ClientSecret,[string]$TargetPrincipalName,[string]$TargetHost,[string]$TargetRealm)
$resource = GetFormattedPrincipal -PrincipalName $TargetPrincipalName -HostName $TargetHost -Realm $TargetRealm
$ClientId = GetFormattedPrincipal -PrincipalName $ClientId -Realm $TargetRealm
$contentType = 'application/x-www-form-urlencoded'
$stsUrl = GetSecurityTokenServiceUrl -Realm $TargetRealm
$oauth2Request = CreateAccessTokenRequestWithClientCredentials -ClientId $ClientId -ClientSecret $ClientSecret -Scope $resource
$oauth2Response = Invoke-RestMethod -Method Post -Uri $stsUrl -ContentType $contentType -Body $oauth2Request
return $oauth2Response
Function GetSecurityTokenServiceUrl([string]$Realm)
return "$Realm/tokens/OAuth/2"
Function CreateAccessTokenRequestWithClientCredentials([string]$ClientId,[string]$ClientSecret,[string]$Scope)
$oauth2Request = @{
'grant_type' = 'client_credentials';
'client_id' = $ClientId;
'client_secret' = $ClientSecret;
'scope' = $Scope;
'resource' = $Scope
return $oauth2Request
function GetFormattedPrincipal([string]$PrincipalName, [string]$HostName, [string]$Realm)
if ($HostName)
return "$PrincipalName/$HostName@$Realm"
return "$PrincipalName@$Realm"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment