Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Azure by (13.1k points)

I was trying to connect to Azure AD using access token via PowerShell. But whenever I tried to run other commands it gives an error:

Get-AzureADUser : Error occurred while executing GetUsers

Code: Authentication_ExpiredToken

Message: Your access token has expired. Please renew it before submitting the request.

HttpStatusCode: Unauthorized

HttpStatusDescription: Unauthorized

HttpResponseStatus: Completed

At C:\Users\kajalchaudhari\Desktop\test_connect.ps1:22 char:1

+ Get-AzureADUser -Top 10

+ ~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo          : NotSpecified: (:) [Get-AzureADUser], ApiException

+ FullyQualifiedErrorId : 


Can anyone help me with this?

1 Answer

0 votes
by (26.7k points)

Basically, the error means that your Graph token has been expired, you need to create a new one. In able to automate this try the below script:

$azureAplicationId ="<application id>"

$azureTenantId= "<tenant id>"

$azurePassword = ConvertTo-SecureString "<client secret>" -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)

Connect-AzAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal

$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext

$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "").AccessToken

Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $


I hope this will work.

Want to become an Azure expert? join azure developer training now!!

Browse Categories