Automating with PowerShell: Connecting to Microsoft Teams with the Secure Application Model

Since the creation of the Secure Application Model more and more modules are supporting it, which is great to see, although at times the documentation is slightly lacking. One of those applications is the MicrosoftTeams module. It’s great to be able to connect to specific teams from your own partner tenant to perform automated tasks or alert on changes that aren’t supposed to happen.

The teams module is a bit sluggish, especially compared to the native Graph solution, but does give us a little bit more information to play with. To be able to connect using the Secure Application Model we have to create two tokens; one normal partner token, the other for the clients tenant. You can use the script below to connect to your clients easily.

The Script

This script uses the PartnerCenter Module, and the MicrosoftTeams Module. You’ll need at least version 2.0, and make sure that no other versions are present. There’s also some difficulties at times when setting specific properties. You might receive an error denied, if you do then that property has to be set with a tenant account itself.

######### Secrets #########
$ApplicationId = 'ApplicationID'
$ApplicationSecret = 'ApplicationSecret' | ConvertTo-SecureString -Force -AsPlainText
$TenantID = 'YourTenantID'
$RefreshToken = 'YourLongRefreshToken'
$UPN = "A-Valid-UPN-In-Your-Tenant"
######### Secrets #########
$credential = New-Object System.Management.Automation.PSCredential($ApplicationId, $ApplicationSecret)

$aadGraphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.windows.net/.default' -ServicePrincipal -Tenant $tenantID 
$graphToken = New-PartnerAccessToken -ApplicationId $ApplicationId -Credential $credential -RefreshToken $refreshToken -Scopes 'https://graph.microsoft.com/.default' -ServicePrincipal -Tenant $tenantID 

Connect-MsolService -AdGraphAccessToken $aadGraphToken.AccessToken -MsGraphAccessToken $graphToken.AccessToken

$customers = Get-MsolPartnerContract -All
foreach ($customer in $customers) {

    $body = @{
        'resource'      = 'https://graph.microsoft.com'
        'client_id'     = $ApplicationId
        'client_secret' = ((New-Object PSCredential "user", $ApplicationSecret).GetNetworkCredential().Password)
        'grant_type'    = "client_credentials"
        'scope'         = "openid"
    }
    $ClientToken = Invoke-RestMethod -Method post -Uri "https://login.microsoftonline.com/$($Customer.tenantID)/oauth2/token" -Body $body -ErrorAction Stop
    $null = connect-microsoftteams -MsAccessToken $ClientToken.access_token -AadAccessToken $aadGraphToken.AccessToken -AccountId $UPN
    get-team
}

And that’s it! this should help you connect to Microsoft Teams resources using the Secure Application Model, as always, Happy PowerShelling.

1 Comment

  1. Dave March 20, 2021 at 6:25 am

    Hello this is great information! I have been able to get this to work myself up to the point of the get-team cmdlet (which works fine)
    I am running into problems with returning information that used to be via the new-csonlinesession such as get-csonlinepstngateway, get-csonlinevoiceroute and other Microsoft Cloud PBX bits and pieces used for Direct Routing.
    The error message for get-csonlinepstngateway looks like this:

    Exception calling “GetSteppablePipeline” with “1” argument(s): “Exception calling “GetRemoteNewCsOnlineSession” with “1” argument(s): “Run either Connect-MicrosoftTeams or new-csonlinesession before running cmdlets.””

    If I run Connect-MicrosoftTeams interactively into my own tenant then running get-csonlinepstngateway works (eventually, it seems quite slow) and returns our gateways for direct routing. It just doesn’t let me do similar for customer tenants and returns the error above.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.