I need to use unattended login for the Microsoft Teams module. To do this I need the Graph and Teams resource tokens to pass to the connection. I have created a http call body for these requests and tested on my machine. They work. When I take the code and place it into the runbook environment i get the "401 Unauthorized" error.
I have given all the proper API permissions to the Service Principal i am using. And gone off this tutorial for the most part, missing the runbooks. teams-powershell-token-auth
Here is the code, minimizing the hardcoding as you would assume.
$Application = Get-AutomationCertificate -Name 'Onboarding-ServicePrincipal.PFX'
$Application
$connectionID = Get-AutomationConnection -Name 'Onboarding-ServicePrincipal'
Connect-ExchangeOnline -AppId $connectionID.ApplicationId -CertificateThumbprint $Application.Thumbprint -Organization "MyCompany.onmicrosoft.com" -verbose
$servicePrincipal = Get-AutomationPSCredential -Name 'Onboarding-ServicePrincipal'
$tenantName = "MyCompany.onmicrosoft.com"
$clientSecret = $servicePrincipal.password
write-output "Connection Details:"
$connectionID.ApplicationId
$servicePrincipal.password
write-output "########################"
$graphResource = "https://graph.microsoft.com/"
$graphTokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $connectionID.ApplicationId
Client_Secret = $clientSecret
}
$graphUri = "https://login.microsoftonline.com/"+$tenantName+"/oauth2/v2.0/token"
$graphUri
$graphTokenResponse = Invoke-RestMethod -Uri $graphUri -Method POST -body $graphTokenBody
write-output "Here is Graph....."
$graphTokenResponse
$teamsResource = "https://api.interfacesrecords.teams.microsoft.com"
$teamsTokenBody = @{
Grant_Type = "client_credentials"
Scope = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default"
Client_Id = $connectionID.ApplicationId
Client_Secret = $clientSecret
}
$teamsUri = "https://login.microsoftonline.com/"+$tenantName+"/oauth2/v2.0/token"
$teamsTokenResponse = Invoke-RestMethod -Uri $teamsUri -Method POST -Body $teamsTokenBody
write-output "Here is Teams...."
$teamsTokenResponse
$servicePrincipal.ClientID