๐ŸŽ New User? Get 20% off your first purchase with code NEWUSER20 ยท โšก Instant download ยท ๐Ÿ”’ Secure checkout Register Now โ†’
Menu

Categories

PowerShell REST API Authentication: Real-World Examples

PowerShell REST API Authentication: Real-World Examples

You have an API endpoint and documentation that says "authenticate with bearer token" or "use OAuth 2.0 client credentials", but working PowerShell REST API authentication examples are sparse. Most API guides show curl commands or language SDKs, leaving you to translate HTTP headers and encoding schemes into PowerShell syntax. This guide shows how to authenticate Invoke-RestMethod and Invoke-WebRequest calls for the most common patterns: API keys in headers or query strings, HTTP basic auth, bearer tokens, and OAuth 2.0 flows.

You will see real headers, credential handling, token refresh logic, and integration with PowerShell's SecretManagement module to avoid hardcoded secrets. Each section includes the errors you will actually encounter (401 Unauthorized, 403 Forbidden, token expiry) and how to fix them. For background on REST fundamentals, see API Basics: REST & JSON Explained.

API Key Authentication in Headers and Query Strings

Many APIs use a static key you pass in a custom header or query parameter. The header name varies: X-API-Key, Api-Key, Authorization with a custom scheme, or something service-specific. Header names are case-insensitive in HTTP, but some proxies and older services expect exact casing. Stick to the documentation's capitalization.

Passing API Keys in Custom Headers

Create a hashtable with the header name and value, then pass it to -Headers:

$apiKey = 'your_api_key_here'
$headers = @{
    'X-API-Key' = $apiKey
}

$response = Invoke-RestMethod -Uri 'https://api.example.com/data' -Headers $headers -Method Get

If the API uses Authorization with a custom prefix (not Bearer), set it directly:

$headers = @{
    Authorization = "Token $apiKey"
}

Invoke-RestMethod -Uri 'https://api.service.com/v1/resource' -Headers $headers

When you get 401 Unauthorized, verify the header name matches the documentation exactly. 403 Forbidden usually means the key is valid but lacks permission for the endpoint. Check your API dashboard for scope or rate limits.

API Keys as Query Parameters

Some APIs expect the key in the URL query string. Build the URI with the parameter:

$apiKey = 'your_api_key_here'
$baseUri = 'https://api.openweathermap.org/data/2.5/weather'
$uri = "$baseUri?q=London&appid=$apiKey"

$weather = Invoke-RestMethod -Uri $uri

For complex queries, use System.Web.HttpUtility to encode parameter values:

Add-Type -AssemblyName System.Web
$city = 'Sรฃo Paulo'
$encoded = [System.Web.HttpUtility]::UrlEncode($city)
$uri = "$baseUri?q=$encoded&appid=$apiKey"

Storing API Keys with SecretManagement

Hardcoded keys in scripts end up in source control or logs. Use the SecretManagement module to retrieve keys at runtime. First, store the key once:

Install-Module Microsoft.PowerShell.SecretManagement -Scope CurrentUser
Install-Module Microsoft.PowerShell.SecretStore -Scope CurrentUser
Register-SecretVault -Name LocalVault -ModuleName Microsoft.PowerShell.SecretStore
Set-Secret -Name OpenWeatherAPIKey -Secret 'your_api_key_here'

In your script, retrieve it with Get-Secret:

$apiKey = Get-Secret -Name OpenWeatherAPIKey -AsPlainText
$headers = @{ 'X-API-Key' = $apiKey }
Invoke-RestMethod -Uri 'https://api.example.com/data' -Headers $headers

For details on configuring vaults and vault permissions, see PowerShell SecretManagement and SecretStore: Stop Hardcoding Credentials.

HTTP Basic Authentication

HTTP basic authentication sends a username and password encoded as Authorization: Basic <base64>. PowerShell's -Credential parameter handles this automatically. Some services use an API key as the username with a blank password. Atlassian products and many CI tools follow this pattern.

Using -Credential with Invoke-RestMethod

Pass a PSCredential object to -Credential, and PowerShell constructs the header:

$cred = Get-Credential -Message 'Enter API credentials'
$response = Invoke-RestMethod -Uri 'https://api.example.com/resource' -Credential $cred -Method Get

For non-interactive scripts, build the credential programmatically:

$username = 'admin'
$password = ConvertTo-SecureString 'P@ssw0rd!' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username, $password)

Invoke-RestMethod -Uri 'https://api.service.com/data' -Credential $cred

When the API uses a token as the username and blank password (common with Jira, Bitbucket, Jenkins):

$apiToken = Get-Secret -Name JiraToken -AsPlainText
$cred = New-Object PSCredential($apiToken, (ConvertTo-SecureString '' -AsPlainText -Force))
Invoke-RestMethod -Uri 'https://yoursite.atlassian.net/rest/api/3/myself' -Credential $cred

Manual Base64 Encoding for Basic Auth

If -Credential does not work (some APIs have non-standard header requirements), construct the header yourself:

$username = 'user@example.com'
$password = 'P@ssw0rd!'
$pair = "$username:$password"
$bytes = [Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [Convert]::ToBase64String($bytes)

$headers = @{
    Authorization = "Basic $base64"
}

Invoke-RestMethod -Uri 'https://api.example.com/resource' -Headers $headers

The official basic authentication specification is RFC 7617.

When Basic Auth Fails: Realm and Character Encoding

If you receive 401 Unauthorized with a WWW-Authenticate: Basic realm="..." header, the server expects credentials for that specific realm. The realm is informational; you cannot set it from the client. Verify your credentials are correct for the service.

Passwords with non-ASCII characters may fail with ASCII encoding. Switch to UTF-8:

$bytes = [Text.Encoding]::UTF8.GetBytes("$username:$password")
$base64 = [Convert]::ToBase64String($bytes)

Some older APIs reject UTF-8; test both encodings if authentication fails unexpectedly.

Bearer Token Authentication

Bearer tokens are opaque strings issued by an authentication service. You pass them in the Authorization header with the Bearer prefix. GitHub, Azure Management API, and most OAuth 2.0 APIs use this pattern.

Adding Bearer Tokens to Headers

Set the Authorization header with the token:

$token = Get-Secret -Name GitHubPAT -AsPlainText
$headers = @{
    Authorization = "Bearer $token"
    Accept        = 'application/vnd.github.v3+json'
}

$repos = Invoke-RestMethod -Uri 'https://api.github.com/user/repos' -Headers $headers

GitHub personal access tokens use Bearer or token as the prefix; both work. Azure uses only Bearer:

$azToken = (Get-AzAccessToken -ResourceUrl 'https://management.azure.com').Token
$headers = @{ Authorization = "Bearer $azToken" }
Invoke-RestMethod -Uri 'https://management.azure.com/subscriptions?api-version=2021-04-01' -Headers $headers

For more on Azure REST API patterns, see PowerShell for Azure Administration 2026.

Token Expiration and Refresh Logic

Most bearer tokens expire. Store the expiry time when you retrieve the token, then check before each call:

$tokenExpiry = [datetime]::UtcNow.AddHours(1)

if ([datetime]::UtcNow -gt $tokenExpiry) {
    # Re-authenticate
    $newToken = Get-NewAccessToken
    $headers['Authorization'] = "Bearer $newToken"
    $tokenExpiry = [datetime]::UtcNow.AddHours(1)
}

Invoke-RestMethod -Uri 'https://api.example.com/data' -Headers $headers

OAuth tokens include an expires_in field (seconds). Add it to the current time:

$authResponse = Invoke-RestMethod -Uri 'https://login.example.com/token' -Method Post -Body $body
$token = $authResponse.access_token
$tokenExpiry = [datetime]::UtcNow.AddSeconds($authResponse.expires_in)

Handling Token Errors

A 401 Unauthorized response with a message like "token expired" or "invalid_token" means you must re-authenticate. Catch the error and retry:

try {
    $response = Invoke-RestMethod -Uri $uri -Headers $headers
} catch {
    if ($_.Exception.Response.StatusCode -eq 401) {
        Write-Warning 'Token expired, re-authenticating...'
        $token = Get-NewAccessToken
        $headers['Authorization'] = "Bearer $token"
        $response = Invoke-RestMethod -Uri $uri -Headers $headers
    } else {
        throw
    }
}

Some APIs return 403 Forbidden for expired tokens. Check the response body for error or message fields to distinguish expiry from insufficient permissions.

OAuth 2.0 Client Credentials Flow

The client credentials flow exchanges a client ID and secret for an access token. Use this for server-to-server calls where no user interaction is needed. Azure Entra ID (formerly Azure AD), Okta, and most enterprise OAuth providers support this flow.

Requesting an Access Token

POST to the token endpoint with form-encoded parameters. For Azure Entra ID, the endpoint is https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token:

$tenantId = 'your-tenant-id'
$clientId = 'your-client-id'
$clientSecret = Get-Secret -Name AzureAppSecret -AsPlainText
$scope = 'https://graph.microsoft.com/.default'

$body = @{
    grant_type    = 'client_credentials'
    client_id     = $clientId
    client_secret = $clientSecret
    scope         = $scope
}

$tokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$authResponse = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded'

$accessToken = $authResponse.access_token
$expiresIn = $authResponse.expires_in

The scope parameter defines what resources the token can access. For Microsoft Graph API, use https://graph.microsoft.com/.default to request all permissions granted to the app registration. For details on configuring app registrations and permissions, see PowerShell and Microsoft Graph API.

If you receive invalid_client, verify the client ID and secret match the app registration. invalid_scope means the requested scope is not configured in the app's API permissions. Check the Azure portal under App registrations โ†’ API permissions.

Using the Token in Subsequent API Calls

Add the token to the Authorization header for each API request:

$headers = @{
    Authorization = "Bearer $accessToken"
    'Content-Type' = 'application/json'
}

$users = Invoke-RestMethod -Uri 'https://graph.microsoft.com/v1.0/users' -Headers $headers

The token is valid for all Graph API endpoints within the granted scope. A 403 Forbidden response means the app lacks the specific permission for that endpoint. Add the permission in the Azure portal, then grant admin consent.

Caching Tokens for Script Duration

Tokens typically expire in 60-90 minutes. Request a new token only when the current one expires. Store the token and expiry time in script-scoped variables:

$script:CachedToken = $null
$script:TokenExpiry = [datetime]::MinValue

function Get-CachedAccessToken {
    if ([datetime]::UtcNow -ge $script:TokenExpiry) {
        Write-Verbose 'Token expired or missing, requesting new token'
        $authResponse = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded'
        $script:CachedToken = $authResponse.access_token
        $script:TokenExpiry = [datetime]::UtcNow.AddSeconds($authResponse.expires_in - 60)
    }
    return $script:CachedToken
}

$token = Get-CachedAccessToken
$headers = @{ Authorization = "Bearer $token" }
Invoke-RestMethod -Uri 'https://graph.microsoft.com/v1.0/users' -Headers $headers

Subtracting 60 seconds from expires_in ensures you refresh the token before it actually expires, avoiding race conditions. For long-running scripts, call Get-CachedAccessToken before each batch of API requests.

OAuth 2.0 Authorization Code Flow for Interactive Scripts

The authorization code flow requires user consent in a browser. The user logs in, grants permissions, and the authorization server redirects to your script with a code. You exchange the code for an access token. Use this for one-off admin scripts where you can open a browser; never for unattended automation.

Build the authorization URL with your client ID, redirect URI, and requested scopes, then open it in the default browser:

$clientId = 'your-client-id'
$redirectUri = 'http://localhost:8080/'
$scope = 'User.Read Mail.Read'
$tenantId = 'your-tenant-id'

$authUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/authorize?" +
           "client_id=$clientId&" +
           "response_type=code&" +
           "redirect_uri=$([uri]::EscapeDataString($redirectUri))&" +
           "scope=$([uri]::EscapeDataString($scope))"

Start-Process $authUrl

The user sees a consent screen listing the requested permissions. After granting consent, the browser redirects to http://localhost:8080/?code=.... Your script must listen on that port to catch the code.

Catching the Redirect with a Local HTTP Listener

Use System.Net.HttpListener to create a temporary web server on localhost:

$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add('http://localhost:8080/')
$listener.Start()

Write-Host 'Waiting for authorization code...'
$context = $listener.GetContext()
$request = $context.Request
$response = $context.Response

$code = $request.QueryString['code']
$responseString = '<html><body>Authentication complete. You can close this window.</body></html>'
$buffer = [Text.Encoding]::UTF8.GetBytes($responseString)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
$response.Close()
$listener.Stop()

Write-Host "Received code: $code"

This is not production-grade: it listens on one request only and has no timeout. For a real admin tool, add error handling and a timeout with GetContextAsync and Wait-Task. If the redirect URI does not match exactly what you registered in the app (including trailing slash), you receive redirect_uri_mismatch.

Exchanging the Authorization Code for a Token

POST the code to the token endpoint with grant_type=authorization_code:

$clientSecret = Get-Secret -Name AzureAppSecret -AsPlainText

$body = @{
    grant_type    = 'authorization_code'
    code          = $code
    redirect_uri  = $redirectUri
    client_id     = $clientId
    client_secret = $clientSecret
}

$tokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$authResponse = Invoke-RestMethod -Uri $tokenUri -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded'

$accessToken = $authResponse.access_token
$refreshToken = $authResponse.refresh_token

The response includes an access token and a refresh token. Store the refresh token securely to obtain new access tokens without re-prompting the user. If you receive invalid_grant with "code already used", the authorization code expired or was reused. Codes are single-use and valid for about 10 minutes.

For public clients (desktop apps, scripts), use PKCE (Proof Key for Code Exchange) to avoid leaking the client secret. Generate a code verifier and challenge before opening the browser, then include code_challenge in the authorization URL and code_verifier in the token request. The Microsoft Entra ID OAuth 2.0 documentation details PKCE parameters.

Authenticating with Certificate-Based Client Auth

Some APIs require a client certificate for mutual TLS authentication. Azure App Service supports this, as do many internal enterprise APIs. You load a certificate from the Windows certificate store and pass it to Invoke-RestMethod with -Certificate.

Loading a Certificate from the Windows Certificate Store

Find the certificate by thumbprint in the current user's personal store:

$thumbprint = 'A1B2C3D4E5F6...'
$cert = Get-ChildItem Cert:\CurrentUser\My | Where-Object Thumbprint -eq $thumbprint

if (-not $cert) {
    throw "Certificate with thumbprint $thumbprint not found"
}

For machine-wide certificates, use Cert:\LocalMachine\My. You need administrative privileges to access LocalMachine stores. If the certificate has a private key, ensure the account running the script has read permission on the private key file. Right-click the certificate in certmgr.msc, choose Manage Private Keys, and add your user.

Passing -Certificate to Invoke-RestMethod

Supply the certificate object to -Certificate:

$response = Invoke-RestMethod -Uri 'https://api.internal.company.com/data' -Certificate $cert -Method Get

PowerShell 7.1 and later support -CertificateThumbprint as a shorthand:

Invoke-RestMethod -Uri 'https://api.internal.company.com/data' -CertificateThumbprint $thumbprint

This searches Cert:\CurrentUser\My automatically. For LocalMachine, still use -Certificate with Get-ChildItem.

Troubleshooting Certificate Errors

If you receive "The remote certificate is invalid according to the validation procedure", the server's certificate chain is not trusted. Import the server's root CA certificate into Cert:\CurrentUser\Root or Cert:\LocalMachine\Root. Never use -SkipCertificateCheck in production; it disables all TLS validation.

When you see "The credentials supplied to the package were not recognized", the private key is missing or inaccessible. Export the certificate with the private key as a PFX, then re-import it with Import-PfxCertificate:

$pfxPath = 'C:\certs\client.pfx'
$pfxPassword = ConvertTo-SecureString 'password' -AsPlainText -Force
Import-PfxCertificate -FilePath $pfxPath -CertStoreLocation Cert:\CurrentUser\My -Password $pfxPassword

Check the certificate's validity period with $cert.NotBefore and $cert.NotAfter. Expired certificates fail immediately with "The certificate has expired". Renew the certificate and update the thumbprint in your script.

Handling Authentication Errors and Retries

Authentication failures manifest as HTTP 401 or 403 status codes. PowerShell throws a Microsoft.PowerShell.Commands.HttpResponseException that wraps the response. You must catch it, inspect the status code and response body, then decide whether to retry or fail. A 401 with an expired token warrants a retry after refreshing credentials; a 403 from insufficient permissions does not.

Parsing 401 and 403 Responses

Catch the exception and check $_.Exception.Response.StatusCode:

try {
    $response = Invoke-RestMethod -Uri $uri -Headers $headers
} catch [Microsoft.PowerShell.Commands.HttpResponseException] {
    $statusCode = $_.Exception.Response.StatusCode.value__
    
    if ($statusCode -eq 401) {
        Write-Warning "401 Unauthorized: Token may be expired or invalid"
        # Retry logic here
    } elseif ($statusCode -eq 403) {
        Write-Error "403 Forbidden: Insufficient permissions for $uri"
        throw
    } else {
        throw
    }
}

The WWW-Authenticate header in the response provides details about the authentication scheme. Parse it to extract the realm or scope:

$wwwAuth = $_.Exception.Response.Headers['WWW-Authenticate']
if ($wwwAuth -match 'realm="([^"]+)"') {
    Write-Verbose "Authentication realm: $($matches[1])"
}
if ($wwwAuth -match 'error="([^"]+)"') {
    Write-Warning "OAuth error: $($matches[1])"
}

Many APIs return JSON error details in the response body. Access it via $_.ErrorDetails.Message:

if ($_.ErrorDetails.Message) {
    $errorDetail = $_.ErrorDetails.Message | ConvertFrom-Json
    Write-Error "API error: $($errorDetail.error) - $($errorDetail.message)"
}

If ErrorDetails.Message is empty, the response body was not captured. This happens when the server sends no body or a non-JSON content type.

Implementing Exponential Backoff for Token Refresh

Retry up to three times on 401, re-authenticating before each retry. Use exponential backoff to avoid hammering the token endpoint:

$maxRetries = 3
$retryCount = 0
$backoffSeconds = 2

while ($retryCount -lt $maxRetries) {
    try {
        $response = Invoke-RestMethod -Uri $uri -Headers $headers
        break
    } catch [Microsoft.PowerShell.Commands.HttpResponseException] {
        if ($_.Exception.Response.StatusCode.value__ -eq 401 -and $retryCount -lt $maxRetries) {
            $retryCount++
            Write-Warning "Attempt $retryCount of $maxRetries failed with 401, refreshing token..."
            
            $token = Get-NewAccessToken
            $headers['Authorization'] = "Bearer $token"
            
            Start-Sleep -Seconds ($backoffSeconds * [math]::Pow(2, $retryCount - 1))
        } else {
            throw
        }
    }
}

The sleep duration doubles each retry: 2, 4, 8 seconds. This gives transient issues time to resolve and prevents rate-limit violations. If all retries fail, the final exception propagates to the caller.

Logging Authentication Failures

Log every authentication failure with a timestamp, endpoint, and status code. Use Write-Error with -ErrorAction Continue to log without stopping the script:

$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
$logMessage = "$timestamp - Auth failed for $uri - Status: $statusCode"

if ($_.ErrorDetails.Message) {
    $errorDetail = $_.ErrorDetails.Message | ConvertFrom-Json
    $logMessage += " - Error: $($errorDetail.error)"
}

Write-Error $logMessage -ErrorAction Continue
Add-Content -Path 'C:\logs\api-auth-errors.log' -Value $logMessage

For production scripts, consider structured logging with JSON or a logging framework. Include the request ID if the API provides one in response headers. Azure APIs return x-ms-request-id, useful for support tickets.

Putting It Together: A Reusable API Client Function

A wrapper function around Invoke-RestMethod centralizes authentication, token refresh, and retry logic. This example supports API key, bearer token, basic auth, and OAuth client credentials flows. Extend it with additional auth types or custom error handling as needed.

Function Structure and Parameters

function Invoke-AuthenticatedRestMethod {
    <#
    .SYNOPSIS
    Calls a REST API with automatic authentication and retry logic.
    
    .PARAMETER Uri
    The API endpoint URL.
    
    .PARAMETER Method
    HTTP method (Get, Post, Put, Delete). Default is Get.
    
    .PARAMETER AuthType
    Authentication type: ApiKey, Bearer, Basic, OAuth.
    
    .PARAMETER ApiKey
    API key for ApiKey auth type.
    
    .PARAMETER Token
    Bearer token for Bearer auth type.
    
    .PARAMETER Credential
    PSCredential for Basic auth type.
    
    .PARAMETER OAuthConfig
    Hashtable with client_id, client_secret, token_uri, scope for OAuth.
    
    .PARAMETER Body
    Request body (hashtable or JSON string).
    #>
    
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Uri,
        
        [string]$Method = 'Get',
        
        [Parameter(Mandatory)]
        [ValidateSet('ApiKey', 'Bearer', 'Basic', 'OAuth')]
        [string]$AuthType,
        
        [string]$ApiKey,
        [string]$Token,
        [PSCredential]$Credential,
        [hashtable]$OAuthConfig,
        [object]$Body
    )
    
    # Build headers based on auth type
    $headers = @{}
    
    switch ($AuthType) {
        'ApiKey' {
            if (-not $ApiKey) { throw 'ApiKey required for ApiKey auth type' }
            $headers['X-API-Key'] = $ApiKey
        }
        'Bearer' {
            if (-not $Token) { throw 'Token required for Bearer auth type' }
            $headers['Authorization'] = "Bearer $Token"
        }
        'OAuth' {
            if (-not $OAuthConfig) { throw 'OAuthConfig required for OAuth auth type' }
            $token = Get-OAuthToken @OAuthConfig
            $headers['Authorization'] = "Bearer $token"
        }
    }
    
    $params = @{
        Uri     = $Uri
        Method  = $Method
        Headers = $headers
    }
    
    if ($AuthType -eq 'Basic') {
        if (-not $Credential) { throw 'Credential required for Basic auth type' }
        $params['Credential'] = $Credential
    }
    
    if ($Body) { $params['Body'] = $Body }
    
    # Retry logic
    $maxRetries = 3
    $retryCount = 0
    
    while ($retryCount -lt $maxRetries) {
        try {
            return Invoke-RestMethod @params
        } catch [Microsoft.PowerShell.Commands.HttpResponseException] {
            if ($_.Exception.Response.StatusCode.value__ -eq 401 -and $retryCount -lt $maxRetries) {
                $retryCount++
                Write-Warning "Retry $retryCount after 401"
                Start-Sleep -Seconds (2 * [math]::Pow(2, $retryCount - 1))
                
                if ($AuthType -eq 'OAuth') {
                    $token = Get-OAuthToken @OAuthConfig -Force
                    $params['Headers']['Authorization'] = "Bearer $token"
                }
            } else {
                throw
            }
        }
    }
}

Integrating Token Refresh and SecretManagement

The function calls a helper Get-OAuthToken that caches tokens and refreshes when expired. Store the token endpoint and credentials in SecretManagement:

function Get-OAuthToken {
    param(
        [string]$client_id,
        [string]$client_secret,
        [string]$token_uri,
        [string]$scope,
        [switch]$Force
    )
    
    if (-not $script:CachedToken -or $Force -or ([datetime]::UtcNow -ge $script:TokenExpiry)) {
        $body = @{
            grant_type    = 'client_credentials'
            client_id     = $client_id
            client_secret = $client_secret
            scope         = $scope
        }
        
        $response = Invoke-RestMethod -Uri $token_uri -Method Post -Body $body -ContentType 'application/x-www-form-urlencoded'
        $script:CachedToken = $response.access_token
        $script:TokenExpiry = [datetime]::UtcNow.AddSeconds($response.expires_in - 60)
    }
    
    return $script:CachedToken
}

Retrieve OAuth credentials from SecretManagement at script start:

$oauthConfig = @{
    client_id     = Get-Secret -Name OAuthClientId -AsPlainText
    client_secret = Get-Secret -Name OAuthClientSecret -AsPlainText
    token_uri     = 'https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token'
    scope         = 'https://graph.microsoft.com/.default'
}

$users = Invoke-AuthenticatedRestMethod -Uri 'https://graph.microsoft.com/v1.0/users' -AuthType OAuth -OAuthConfig $oauthConfig

Usage Examples

Call the function with different auth types:

# API key
$data = Invoke-AuthenticatedRestMethod -Uri 'https://api.example.com/data' -AuthType ApiKey -ApiKey 'your_key'

# Bearer token
$repos = Invoke-AuthenticatedRestMethod -Uri 'https://api.github.com/user/repos' -AuthType Bearer -Token $githubToken

# Basic auth
$cred = Get-Credential
$response = Invoke-AuthenticatedRestMethod -Uri 'https://api.service.com/resource' -AuthType Basic -Credential $cred

For POST requests with JSON bodies, pass a hashtable to -Body:

$newUser = @{
    displayName       = 'John Doe'
    userPrincipalName = 'john@contoso.com'
    mailNickname      = 'johnd'
}

Invoke-AuthenticatedRestMethod -Uri 'https://graph.microsoft.com/v1.0/users' -Method Post -AuthType OAuth -OAuthConfig $oauthConfig -Body ($newUser | ConvertTo-Json)

Checklist: Before You Call That API in Production

  • Store secrets in SecretManagement or Azure Key Vault, never hardcoded or in plain-text config files. See PowerShell SecretManagement and SecretStore for setup steps.
  • Validate API permissions in the provider's admin console. A 403 at runtime means your app or token lacks the required scope.
  • Implement retry logic with exponential backoff for 401 and transient network errors. Log every retry with timestamp and endpoint.
  • Check token expiry before each request in long-running scripts. Cache tokens and refresh proactively, not reactively.
  • Use TLS 1.2 or higher. Set [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 at script start if targeting older PowerShell versions.
  • Handle rate limits. Parse Retry-After or X-RateLimit-Reset headers in 429 responses and sleep until the limit resets.
  • Log authentication failures to a file with request ID, status code, and error message. Include enough detail for support tickets.
  • Test error paths. Intentionally use an invalid token or revoke permissions to verify your retry and logging logic works.

For deeper coverage of Microsoft Graph API authentication patterns, including delegated permissions and app-only flows, see PowerShell and Microsoft Graph API.

Frequently Asked Questions

How do I pass an API key in a PowerShell REST API call?

Create a hashtable with the header name (often X-API-Key or Authorization) and the key value, then pass it to -Headers: $headers = @{ 'X-API-Key' = 'your_key' }; Invoke-RestMethod -Uri $uri -Headers $headers. For query parameters, append ?api_key=your_key to the URI. Always retrieve the key from SecretManagement, not hardcoded strings.

What is the difference between bearer token and basic authentication?

Basic authentication sends a base64-encoded username and password in the Authorization: Basic header on every request. Bearer token authentication sends a token issued by an OAuth provider in Authorization: Bearer. Tokens expire and can be scoped to specific permissions; basic credentials do not expire unless changed. Bearer tokens are preferred for APIs that support OAuth 2.0.

How do I refresh an OAuth access token in PowerShell?

Store the refresh_token from the initial token response. When the access token expires, POST to the token endpoint with grant_type=refresh_token and the refresh token: $body = @{ grant_type='refresh_token'; refresh_token=$refreshToken; client_id=$clientId; client_secret=$clientSecret }; Invoke-RestMethod -Uri $tokenUri -Method Post -Body $body. The response contains a new access token and sometimes a new refresh token.

Why am I getting 401 Unauthorized with Invoke-RestMethod?

Common causes: expired token, incorrect header name or format, wrong credentials, or the token lacks the required scope. Check the WWW-Authenticate header in the response for details. Verify you are setting Authorization correctly (Bearer token, not Bearer: token). For OAuth, confirm the scope matches the API's requirements and the app has admin consent if needed.

Can I use PowerShell SecretManagement to store API tokens?

Yes. Install the SecretManagement and SecretStore modules, register a vault, then store tokens with Set-Secret -Name TokenName -Secret 'token_value'. Retrieve them with Get-Secret -Name TokenName -AsPlainText. For unattended scripts, configure the SecretStore vault with -Authentication None or use Azure Key Vault as the vault provider. See Invoke-RestMethod documentation for parameter details.

Share this article:
Thomas Ellison
About the Author

Thomas Ellison

Database Administration, Applied Mathematics, Technical Education, Documentation

Thomas Ellison is a database administrator and mathematics teacher with a strong focus on structured thinking, data integrity, and reliable system design.

He has extensive experience managing database systems in professional environments, ensuring performance, consistency, and long-term maintainability. His work includ...

Database Administration SQL Data Modeling Performance Optimization Mathematical Foundations

Stay Updated

Subscribe to our newsletter for the latest tutorials, tips, and exclusive offers.