iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔗

Calling SharePoint Online REST APIs with PowerShell

に公開

Introduction

Following up on my previous article, I will explain how to execute REST APIs using Invoke-RestMethod.

https://zenn.dev/karamem0/articles/2016_12_10_000000

Review of OAuth

To execute SharePoint Online REST APIs, authorization via Azure AD OAuth is required. Azure AD supports several authorization flows for obtaining access tokens:

  • Authorization Code Grant
  • Implicit Grant
  • Client Credentials Grant
    • Shared Secret
    • Certificate
  • Resource Owner Password Credentials Grant
  • Device Flow

Authorization Code and Implicit Grants are intended for applications with a UI (web browser). Therefore, when using PowerShell, you must choose another method. Here is a brief comparison of the other methods:

Authorization Flow Authorization Difficulty Unattended Security
Client Credentials (Shared Secret) Application Low Yes Low
Client Credentials (Certificate) Application High Yes High
Device Flow User Medium No -

Each has its pros and cons, so please choose the one that suits your purpose. In this article, we will use Device Flow for authentication.

Execution Steps

Registering the Application

Register an Azure AD application with an appropriate name from the Azure management portal.

Select Office 365 SharePoint Online for the API to be used.

Select the permissions. For this sample, we are granting full control, but in a real-world scenario, choose the appropriate permissions.

This completes the initial setup.

Creating the Script

While C# requires the use of WebClient or HttpClient, PowerShell allows for concise code by using Invoke-RestMethod.

$tenantId = "{{tenant-id}}"
$resourceUri = "{{resource-uri}}"
$clientId = "{{client-id}}"

# Get device code
$uri = "https://login.microsoftonline.com/" + $TenantId + "/oauth2/devicecode?" + `
       "resource=" + [System.Uri]::EscapeDataString($resourceUri) + "&" + `
       "client_id=" + $clientId
$headers = @{
    "Accept" = "application/json"
}
$result = Invoke-RestMethod -Method "Get" -Uri $uri -Headers $headers

$userCode = $result.user_code
$deviceCode = $result.device_code

Write-Output $userCode
Start-Process "https://aka.ms/devicelogin"

Read-Host | Out-Null

# Get token
$uri = "https://login.microsoftonline.com/" + $TenantId + "/oauth2/token"
$headers = @{
    "Accept" = "application/json"
    "Content-Type" = "application/x-www-form-urlencoded"
}
$body = "resource=" + [System.Uri]::EscapeDataString($resourceUri) + "&" + `
        "client_id=" + $clientId + "&" + `
        "grant_type=device_code&" + `
        "code=" + [System.Uri]::EscapeDataString($deviceCode)

$result = Invoke-RestMethod -Method "Post" -Uri $uri -Headers $headers -Body $body

$accessToken = $result.access_token

# Get site title
$uri = $resourceUri + "/_api/web/title"
$headers = @{
    "Accept" = "application/json"
    "Authorization" = "Bearer " + $accessToken
}
$result = Invoke-RestMethod -Method "Get" -Uri $uri -Headers $headers
Write-Output $result.value

# Get list of documents
$uri = $resourceUri + "/_api/web/getfolderbyserverrelativeurl('/Shared%20Documents')/files"
$headers = @{
    "Accept" = "application/json"
    "Authorization" = "Bearer " + $accessToken
}
$result = Invoke-RestMethod -Method "Get" -Uri $uri -Headers $headers
$result.value | select Name, TimeCreated, TimeLastModified

Execution Results

When executed, a code will be displayed in the prompt. The script will wait for input until authentication is completed. A browser will also launch; please enter the code displayed in the console.

Confirm the application name and click Continue. You will be prompted to sign in with your organizational account; enter your username and password.

Once signed in, authentication is complete. It is safe to close the browser.

Press the Enter key in the prompt to resume the script, which will then retrieve the site title and the list of files in the document library from SharePoint Online.

Conclusion

For SharePoint Online alone, CSOM is more convenient. However, when integrating with other Office 365 services, using REST APIs provides the advantage of a unified development method.

As for how CSOM authenticates to SharePoint Online, it appears to use a method called BPOSIDCRL. As the name BPOS suggests, it is a legacy method, so it is interesting to see how long it will continue to be supported.

Discussion