You need an MSGraph token, not an AAD token. Here is some sample powershell I pieced together last week to do this. Notice: it uses the MSI of an Azure Function to access a Key Vault to get the secret for the AppID, and then generates a Graph token with the AppID and the secert. Also note the Connect-MicrosoftTeams command parameters. It took forever to figure those out :| Good luck!
using namespace System.Net
using namespace System.Web
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Define AppId, secret and scope, your tenant name and endpoint URL
$Scope = "https://graph.microsoft.com/.default"
$TenantName = "your tenant name here"
$AppId = "your appID here"
$AppSecretURI = "your vault secret URI here"
#Import-Module 'D:\Home\site\wwwroot\HttpTrigger1\Modules\MicrosoftTeams\2.1.0\MicrosoftTeams.psd1'
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
# Interact with query parameters or the body of the request.
$name = $Request.Query.Name
if (-not $name) {
$name = $Request.Body.Name
}
$body = "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
if ($name) {
# get access token with MSI. For more details, please refer to https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity#rest-protocol-examples
$tokenAuthURI = $Env:MSI_ENDPOINT + "?resource=https://vault.azure.net&api-version=2017-09-01"
$tokenResponse = Invoke-RestMethod -Method Get -Headers @{"Secret"="$env:MSI_SECRET"} -Uri $tokenAuthURI
$accessToken = $tokenResponse.access_token
# get secret value
$headers = @{ 'Authorization' = "Bearer $accessToken" }
$queryUrl = $AppSecretURI + "?api-version=7.0"
$keyResponse = Invoke-RestMethod -Method GET -Uri $queryUrl -Headers $headers
$AppSecret = $keyResponse.value
$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
# Create body
$Body = @{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
grant_type = 'client_credentials'
}
# Splat the parameters for Invoke-Restmethod for cleaner code
$PostSplat = @{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
# Create string by joining bodylist with '&'
Body = $Body
Uri = $Url
}
# Request the token!
$Request = Invoke-RestMethod @PostSplat
$Request
$token = $Request.access_token
Connect-MicrosoftTeams -TenantId $TenantName -AccountId $AppId -AadAccessToken $token -MsAccessToken $token
#Your Command Here
$team = Get-Team
Write-Host "Team Count to show connection success::::" ($team).count
$status = [HttpStatusCode]::OK
$body = "New Team Name is $team"
}
else {
$status = [HttpStatusCode]::BadRequest
$body = "Please pass a name on the query string or in the request body."
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})