Created
May 8, 2020 13:15
-
-
Save OlafD/6e45ee423b6d24627125cc2996090e5a to your computer and use it in GitHub Desktop.
Short example on how to use an app registration to call rest services for SharePoint Online from PowerShell.
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
# set variables | |
$clientId = "{id of your registered app}" | |
$clientSecret = "{secret of your registered app}" | |
$realm = "{id of the tenant}" # could be found in the registered app in Azure Active Directory | |
$principal = "00000003-0000-0ff1-ce00-000000000000" # this is the SharePoint resource | |
$targetHost = "{SharePoint root of the tenant}" # example: mytenant.sharepoint.com | |
# url used for the rest call later to test the access | |
$spRestUrl = "https://mytenant.sharepoint.com/sites/test-site/_api/web/lists" # make the necessary changes for your environment | |
# get the access token for the registered app | |
$body = @{ | |
grant_type = "client_credentials" | |
client_id = "$clientId@$realm" | |
client_secret = $clientSecret | |
resource = "$principal/$targetHost@$realm" | |
} | |
$headers = @{ | |
ContentType = "application/x-www-form-urlencoded" | |
} | |
# also see https://docs.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs | |
$uri = "https://accounts.accesscontrol.windows.net/$realm/tokens/OAuth/2" | |
$response = Invoke-WebRequest -Uri $uri -Method Post -Body $body -Headers $headers | |
$responseContent = $response.Content | |
$jsonContent = ConvertFrom-Json $responseContent | |
$accessToken = $jsonContent.access_token | |
# make a rest call against the SharePoint site | |
$headers = @{ | |
Authorization = "Bearer $accessToken" | |
Accept = "application/json;odata=nometadata" | |
} | |
$response = Invoke-WebRequest -Uri $spRestUrl -Method Get -Headers $headers | |
$responseContent = $response.Content | |
$jsonContent = ConvertFrom-Json $responseContent | |
$jsonContent.value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment