Home Get an authentication token in Azure Function
Post
Cancel

Get an authentication token in Azure Function

Summary

Sample code to get an authentication token in an Azure Function. This code snippet shows how to get an authentication token using the client credentials flow in an Azure Function.

PowerShell Function to Get an Authentication Token

This is content of run.ps1 file in Azure Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using namespace System.Net
param($Request, $TriggerMetadata)

# Initialize logging and environment variables
$tenantId = $env:TENANT_ID_HEI_LTT
$environmentUrl = $env:ENV_URL_HEI_LTT
$spAppId = $env:SPN_ID_HEI_LTT
$spSecret = $env:SPN_SECRET_HEI_LTT
$logLevel = $env:LOG_LEVEL
$accessToken = $null


function Get-AuthToken {
    param (
        [Parameter(Mandatory)]
        [string]$tenantId,
        [Parameter(Mandatory)]
        [string]$spAppId,
        [Parameter(Mandatory)]
        [string]$spSecret,
        [Parameter(Mandatory)]
        [string]$environmentUrl
    )
    $tokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
    $tokenBody = @{
        client_id     = $spAppId
        scope         = "$environmentUrl/.default"
        client_secret = $spSecret
        grant_type    = 'client_credentials'
    }

    $response = Invoke-RestMethod -Uri $tokenUri -Method 'Post' -ContentType 'application/x-www-form-urlencoded' -Body $tokenBody
    $token = @{
        "access_token" = $response.access_token
        "token_type" = "Bearer"
        "expires_in" = 3600
    }

    return $token.access_token 
}

try {
    try {
        $accessToken = Get-AuthToken -tenantId $tenantId -spAppId $spAppId -spSecret $spSecret -environmentUrl $environmentUrl   
    }
    catch {
        Write-Log "ERROR: Failed to retrieve access token." -LogLevel $logLevel 
        throw
    }

    $success = $true
    $response = @{
        "token" = $accessToken
        "success" = $success
    }
    Write-Log $response.success -LogLevel $logLevel
}
catch {
    $success = $false
     $response = @{
         "token" = $null
         "success" = $success
     }
     Write-Output "ERROR: Failed to retrieve minimum delivery quantity pallet places. $_"
     Write-Error $Error[0]
}

if ($response) {
    $body = $response | ConvertTo-Json
}else{
    $body = "No response"
}

Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
    StatusCode = if ($response.success) { [HttpStatusCode]::OK } else { [HttpStatusCode]::BadRequest }
    Body = $body
})


This post is licensed under CC BY 4.0 by the author.

Tip of the day - How to create effective prompts for M365 CoPilot

Display training checklist in SharePoint Framework web part