Authentication & Headers
When integrating PowerShell with REST APIs, authentication and headers are critical for secure and reliable communication. This section covers OAuth 2.0, API keys, and custom headers, along with practical examples for PowerShell implementation.
OAuth 2.0 Authentication¶
OAuth 2.0 is a standard for delegated access, commonly used with services like Microsoft Graph or Azure APIs. PowerShell can leverage the Microsoft.Identity.Client (MSAL) module to handle token acquisition.
Example: Client Credentials Flow¶
# Install the MSAL module if needed
# Install-Module -Name Microsoft.Identity.Client
# Configure client app details (tenant ID, client ID, client secret)
$tenantId = "your-tenant-id"
$clientId = "your-client-id"
$clientSecret = "your-client-secret"
# Acquire access token
$tokenResponse = Get-MsalToken -ClientId $clientId -ClientSecret $clientSecret -TenantId $tenantId -Scope "https://graph.microsoft.com/.default"
# Use token in API request
$headers = @{
"Authorization" = "Bearer $($tokenResponse.AccessToken)"
"Content-Type" = "application/json"
}
$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users" -Method Get -Headers $headers
Example: Authorization Code Flow (Interactive)¶
$authResult = Get-MsalTokenCache | Get-MsalAccount | ForEach-Object {
$authResult = Get-MsalToken -Account $($_.Account) -Scope "User.Read"
$authResult
}
$headers = @{
"Authorization" = "Bearer $($authResult.AccessToken)"
}
$response = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/me" -Method Get -Headers $headers
API Key Authentication¶
API keys are simple but effective for server-to-server communication. They are typically included in headers like Authorization (with Bearer prefix) or custom headers like X-API-Key.
Example: Using a Bearer Token¶
$apiKey = "your-api-key"
$headers = @{
"Authorization" = "Bearer $apiKey"
"Content-Type" = "application/json"
}
$response = Invoke-RestMethod -Uri "https://api.example.com/data" -Method Get -Headers $headers
Example: Custom Header for API Key¶
$apiKey = "your-api-key"
$headers = @{
"X-API-Key" = $apiKey
"Accept" = "application/json"
}
$response = Invoke-RestMethod -Uri "https://api.example.com/secure-endpoint" -Method Get -Headers $headers
Custom Headers¶
Custom headers provide flexibility for logging, session tracking, or specifying request formats. Use the -Headers parameter in Invoke-RestMethod to include them.
Example: Logging Request ID¶
$requestId = [Guid]::NewGuid().ToString()
$headers = @{
"X-Request-ID" = $requestId
"Content-Type" = "application/json"
}
$body = @{
"message" = "Test payload"
} | ConvertTo-Json
$response = Invoke-RestMethod -Uri "https://api.example.com/log" -Method Post -Headers $headers -Body $body
Best Practices¶
- Always use HTTPS to encrypt data in transit.
- Store secrets securely (e.g., Azure Key Vault, environment variables).
- Rotate tokens/API keys periodically and avoid hardcoding credentials in scripts.
- Validate responses and handle errors gracefully (e.g., 401 Unauthorized for expired tokens).
Key takeaways¶
- OAuth 2.0 (via MSAL) enables secure delegated access for cloud APIs.
- API keys can be embedded in headers like
Authorizationor custom fields. - Custom headers provide flexibility for metadata, logging, or request context.
- Secure storage, HTTPS, and error handling are critical for production-grade integrations.