SOLVED

Authenticating with an access token Connect-MicrosoftTeams

Brass Contributor
Has anyone tried authenticating with an access token (using -AadAccessToken or -MsAccessToken)? The old version of New-CsOnlineSession had an -OAuthAccessToken param, which accepted a jwt with the PS permissions in the scope, which one could obtain silently, and so avoid login.

New-CsOnlineSession has been dropped and the SfB Connector is end of life in July and Connect-MicrosoftTeams does appear to support token for the telephony functions.
135 Replies
Hi everyone, I just tested the new PS Teams module 3.1.1. I still get the same error (Connect-MicrosoftTeams : Object reference not set to an instance of an object.),
I hope they will fix it on March...

@Iulian_Simonn 

 

After creating an App Registration in Azure Active Directory with permissions like this:

doreladam_0-1644506533297.png

I'm able to connect to Teams using:

$tenantName = ""  
$clientId = ""
$clientSecret = ""
$username = ""
$password = ""

$uri = "https://login.microsoftonline.com/$tenantName/oauth2/v2.0/token"

$body = @{  
   Grant_Type    = "password";
   Scope         = "https://graph.microsoft.com/.default"  
   Client_Id     = $clientId;
   Client_Secret = $clientSecret;
   Username      = $username; 
   Password      = $password; 
}   
$graphTokenResponse = Invoke-RestMethod -Method POST -Uri $uri -Body $body
$graphToken = $graphTokenResponse.access_token

$body = @{  
   Grant_Type    = "password"  # client_credentials
   Scope         = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default"
   Client_Id     = $clientId  
   Client_Secret = $clientSecret  
   Username      = $username  
   Password      = $password  
}   
$teamsTokenResponse = Invoke-RestMethod -Method POST -Uri $uri -Body $body
$teamsToken = $teamsTokenResponse.access_token

Connect-MicrosoftTeams -AccessTokens @($graphToken, $teamsToken)

Get-CsCallQueue

Disconnect-MicrosoftTeams

 

But the Get-CsCallQueue call fails with:

doreladam_1-1644506752596.png

 

The same issue still exists on preview version 3.2.
Looks like this is ROPC flow, not client credentials flow.

The most likely cause of the error is that the module is searching for the "UPN" value of the token i.e. the user name. Authorization flow works because it's done in the context of a user and therefore the token has a UPN. Client credentials does not work because there is no user context and no UPN.
@doreladam, I think you may be getting the HTTP 403 response with Get-CsCallQueue because the user $username you are impersonating may not have sufficient permissions to administer Teams/Skype for Business. Have you tried this with a global admin account? I can't, because all our admin accounts have multifactor authentication enabled, and that causes Connect-MicrosoftTeams to fail.

@PhoneMe007 

MicrosoftTeams PowerShell Module 4.0.0 has been released 

https://www.powershellgallery.com/packages/MicrosoftTeams/4.0.0
I've tested it with App Only Authentication (Certificate / ClientSecret). Still does not work

AndresBohren_0-1646741533293.png

In my Microsoft Case [Case #:28612860] they said that the ETA will be early Q2 2022. I guess we still have to wait.

 

Regards Andres

 

I've had the same problem with several different versions of the MicrosoftTeams modules...

Including:
Install-Module -Name MicrosoftTeams -RequiredVersion 2.3.2-preview -AllowPrerelease

Install-Module -Name MicrosoftTeams -RequiredVersion 3.0.0

Install-Module -Name MicrosoftTeams -RequiredVersion 3.1.1

Install-Module -Name MicrosoftTeams -RequiredVersion 4.0.0
Install-Module -Name MicrosoftTeams -RequiredVersion 4.0.1-preview -AllowPrerelease

My tokens are correct:

PS> $($graphToken | Get-JWTDetails).Roles | sort
AppCatalog.Read.All
AppCatalog.ReadWrite.All
Directory.Read.All
Directory.ReadWrite.All
Group.Read.All
Group.ReadWrite.All
People.Read.All
Schedule.Read.All
Schedule.ReadWrite.All
Team.ReadBasic.All
TeamSettings.Read.All
User.Read.All
UserShiftPreferences.Read.All
UserShiftPreferences.ReadWrite.All

PS> $($teamsToken | Get-JWTDetails).Roles | sort
application_access
application_access_custom_sba_appliance



All of them give me this:
 

 

PS> Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken")
Connect-MicrosoftTeams : Object reference not set to an instance of an object.
At line:1 char:1
+ Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : AuthenticationError: (:) [Connect-MicrosoftTeams], NullReferenceException
+ FullyQualifiedErrorId : Connect-MicrosoftTeams,Microsoft.TeamsCmdlets.Powershell.Connect.ConnectMicrosoftTeams

Connect-MicrosoftTeams : Object reference not set to an instance of an object.
At line:1 char:1
+ Connect-MicrosoftTeams -AccessTokens @("$graphToken", "$teamsToken")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Connect-MicrosoftTeams], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Microsoft.TeamsCmdlets.Powershell.Connect.ConnectMicrosoftTeams​

 

 

 

Hi@sjackson340 

 

As written here - i have running code (with Delegated Permissions)

https://techcommunity.microsoft.com/t5/teams-developer/authenticating-with-an-access-token-connect-m...

 

Using Delegated Permissions does not make sense - i totally agree :)

I had a Ticket open at Microsoft #28612860. It was closed with the ETA of Mid April for the Fix. So we will see.

 

Tested a code with Application Permissions with Teams PowerShell Module 4.1.0 - still does not work.

 

Regards

Andres

Hi Andres,

that's great to hear. hopefully MS will fix this, an the connect-microsoftTeams will work as expected with ApplicationPermissions (include using a certificate an not an AppSecret)....

Br

@Ronar85  and @Andres Bohren 

 

Thanks for the link and comments. Still cannot get it working...

#Install-Modules
Install-Module JWTDetails #Not needed - just for debug
Install-Module MSAL.PS -MaximumVersion 4.36.1.2 -acceptlicense -SkipPublisherCheck -force
Install-Module MicrosoftTeams -MaximumVersion 3.0.0 -force

#Import Modules
Import-module -name JWTDetails
Import-Module MSAL.PS -MaximumVersion 4.36.1.2
Import-Module MicrosoftTeams -MaximumVersion 3.0.0
Get-Module

#Clear TokenCache
Clear-MsalTokenCache

#Prep
Add-Type -AssemblyName System.Web
$ImpersonationUPN="Email address removed"
$TenantID="TENANTNAME-OR-TENANTID"
$ApplicationID="REDACTED"
$ImpersonationUPN="Email address removed"
$ClientSecret="REDACTED" 

#TeamsAccessToken
$Scope = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default" 
$Token = Get-MsalToken -ClientId $ApplicationID -TenantId $TenantId -Scope $Scope -ClientSecret $(ConvertTo-SecureString -String $ClientSecret -AsPlainText -force)
$TeamsAccessToken = $Token.AccessToken
Get-JWTDetails $TeamsAccessToken
 
#GraphAccessToken
$Scope = "https://graph.microsoft.com/.default"
$Token = Get-MsalToken -ClientId $ApplicationID -TenantId $TenantId -Scope $Scope -ClientSecret $(ConvertTo-SecureString -String $ClientSecret -AsPlainText -force)
$GraphAccessToken = $Token.AccessToken
Get-JWTDetails $GraphAccessToken
 

#Connect To MS TEAMS
Connect-MicrosoftTeams -AccessTokens @($GraphAccessToken,$TeamsAccessToken) -AccountId $($impersonatedUser.id) -verbose #Error: Parameter set cannot be resolved using the specified named parameters.
Connect-MicrosoftTeams -LogLevel Verbose -LogFilePath %temp%\Connect-MSTeams.log -AccessTokens @($GraphAccessToken,$TeamsAccessToken)
notepad %temp%\Connect-MSTeams.log 

sjackson340_0-1649081690087.png

sjackson340_1-1649081729136.png

 

 

Debug:

2022-04-04T13:55:38.2302931Z,Error ,Connect-MicrosoftTeams.ProcessRecord,
System.NullReferenceException - Object reference not set to an instance of an object.. at Microsoft.TeamsCmdlets.Powershell.Connect.RMProfileClient.GetTokenClaimValue(JsonWebToken webToken, String value)
 at Microsoft.TeamsCmdlets.Powershell.Connect.RMProfileClient.ProcessProvidedAccessTokens(AzureAccount account, String tenantId)
 at Microsoft.TeamsCmdlets.Powershell.Connect.RMProfileClient.AcquireAccessToken(AzureAccount account, AzureEnvironment environment, String tenantId, SecureString password, AuthenticationFlow authFlow)
 at Microsoft.TeamsCmdlets.Powershell.Connect.RMProfileClient.Login(AzureAccount account, AzureEnvironment environment, String tenantId, SecureString password, AuthenticationFlow authFlow)

 

Hi @sjackson340 ,

 

the part using a ClientID, ClientSecret, Username & Password worked for me, after changing the AppRegistrations Role Memberships and API Permissions.

 

Used Parts of the code @Andres Bohren  mentioned here (https://techcommunity.microsoft.com/t5/teams-developer/authenticating-with-an-access-token-connect-m... :(

$tenantName = "<REMOVEDNAME>.onmicrosoft.com"  
$clientId = "<APPREGISTRATION ID>"
$clientSecret = "<APPREGISTRATIONSECRET>"
$username = "<MYSERVICEUSER>@<REMOVEDNAME>.onmicrosoft.com"
$password = "<MYPWD>"

$uri = "https://login.microsoftonline.com/$tenantName/oauth2/v2.0/token"

$body = @{  
   Grant_Type    = "password";
   #Grant_Type    = "client_credentials";
   Scope         = "https://graph.microsoft.com/.default"  
   Client_Id     = $clientId;
   Client_Secret = $clientSecret;
   Username      = $username; 
   Password      = $password; 
}   
$graphTokenResponse = Invoke-RestMethod -Method POST -Uri $uri -Body $body
$graphToken = $graphTokenResponse.access_token

$body = @{  
   Grant_Type    = "password"  # client_credentials
   #Grant_Type    = "client_credentials"
   Scope         = "48ac35b8-9aa8-4d74-927d-1f4a14a0b239/.default"
   Client_Id     = $clientId  
   Client_Secret = $clientSecret  
   Username      = $username  
   Password      = $password  
}   
$teamsTokenResponse = Invoke-RestMethod -Method POST -Uri $uri -Body $body
$teamsToken = $teamsTokenResponse.access_token

Connect-MicrosoftTeams -AccessTokens @($graphToken, $teamsToken)

 

The App Registration itself i've extented with the following Delegated Rights:

Ronar85_0-1649107611272.png

 

and as this step has to be done by Exchange Management (Dokumented by MS here), i've added the Appregistration to the Teams administrators, thinking, this cloud be the right step, as it's also needed for EXO Management. (i'm using the same AppRegistration for EXO Management)

Ronar85_1-1649107874825.png

 

After the connect...

Ronar85_2-1649108375149.png

... i was able to create new Teams...

Ronar85_3-1649108440747.png

.. and also Query the CSOnlineUser Data...

Ronar85_4-1649108498721.png

also the new Set-CSOnlineVoiceUser seems to work - but i've got no tenant numbers in my development tenant right now :) 

 

But i totally agree with @Andres Bohren statement, that this has to work with Application Permissions only in combination using a certificate as authenticator as well! Please guys @microsoft-msteams fix this!

 

BR 

 

@Ronar85 

Your statement about 'application-only permissions' seems a little confusing to me. Surely all of the following types of authentication should work; without mixing a combination of them up...

  • ClientID/AppID and Secret
  • Username and password (with specific MFA bypass configured)
  • ClientID and Certificate

Happy to extend my code to use a username and password as well as ClientID and Secret.

 

Can you confirm any additional Azure Roles applied to the username in your last example?

Folks, a couple newer versions of the module since last post. Is MS any closer to allowing CBA or app ID / secret auth work for the Teams module?

@Robert Leist and @sjackson340 

I recently had a MS Case open to clarify the Timeline.

Answer from Microsoft:

Per the latest update,  if everything goes well, end of Sept 2022 is ETA and as well we recommended to have your tenant in preview rollout to prioritize feature enablement.

 

Regards

Andres

@Andres Bohren https://docs.microsoft.com/en-us/powershell/module/teams/connect-microsoftteams?view=teams-ps would indicate that certificatethumbprint was available at some point but removed in preview 2.4.1, is the expectation that this will be reintroduced then or am I as confused as normal?

 

Given basic auth goes away in October it’s pretty poor that the Teams module doesn’t seem to be able to auth via other means when MFA is enforced by conditional access (unless I’m missing a trick, which is very possible)

Tested with the newly released 4.7.0 Powershell Module (September 2022) - Microsoft Teams PowerShell Release Notes - Microsoft Teams | Microsoft Docs

 

Still unable to auth using token / appid only -

PS C:\Windows\system32> Connect-MicrosoftTeams -AccessTokens @($GraphAccessToken,$TeamsAccessToken)
Connect-MicrosoftTeams : Object reference not set to an instance of an object.

 

@pkecun 

I am facing same issue. Need to get access to MS Teams Powershell cmdlets via api permissions.

Is there any ETA on this?

The Teams PowerShell module for Microsoft Teams has been released as a preview version (2.1.0) which supports modern authentication and is fully functional. The likelihood is that this version will be pushed through to general availability quite soon as a result of this fast process.
If you would like more information, please take a look at this link.

@Vishal170  App-based authentication appears to be working as of MicrosoftTeams PowerShell module 4.7.1-preview.  MS Graph cmdlets work fine, however there still appear to be issues with CS cmdlets.  I now get the following error when I attempt to run Get-CsOnlineUser:

 

2022-09-19 10_53_49-Window.png

I get the same error regardless of whether the WinRM service is running on my local PC.

@bauclair
You need to add your AzureAD App to the Azure AD Role "Skype4B Administrator".
After that it works

Regards
Andres