azure - 使用 powershell 使用访问 token 连接到 azure ad

标签 azure powershell azure-active-directory

我正在编写一个 powershell 脚本来使用访问 token 连接到 azure ad。我正在使用以下命令:

Connect-AzureAD -TenantId "$tenantId"  -AadAccessToken $tokenResponse.access_token -AccountId "$appId"

我已授予应用程序“Contirbute”和“全局管理员”角色,并且应用程序具有所有必需的权限。

当我执行脚本时,我可以连接到 Azure AD,但如果我在此之后尝试运行后续命令,则会出现以下错误。

请进一步帮助我。

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 : 
Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Open.AzureAD16.PowerShell.GetUser

最佳答案

该错误表示您传递的 AAD Graph token 已过期,您需要传递新的 token 。

或者,如果您想自动执行此操作,可以按照以下步骤操作。

1.首先请确保您已经安装了 Az模块。然后获取application id, tenant id , client secret AD 应用程序的全局管理员。

2.然后运行下面的脚本,在我这边运行得很好。

$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, "https://graph.windows.net").AccessToken
Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id

Get-AzureADUser

enter image description here

关于azure - 使用 powershell 使用访问 token 连接到 azure ad,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63196010/

相关文章:

sql-server - Azure SQL 服务器数据库 [Win32Exception (0x80004005) : Access is denied]

azure - 使用 powershell,如何为路径段中版本的 api 管理服务创建 api?

azure - 运行 Azure 函数将出现 .net 4.7.1 安装提示对话框

Webjob DashboardConnectionString 和 StorageConnectionString 的 Azure SAS token

PowerShell 3 参数

powershell - 按属性名称过滤 cim 实例类

azure - 使用 Get-MgUser 查找用户管理器 UPN

powershell - 当文件没有标题行时,如何使用 Import-CSV 导入制表符分隔的文本文件?

python - 来自 Python 的 Microsoft Graph API 调用

PowerShell - 使用 Microsoft 帐户连接到 Azure Active Directory