使用Connect-AzAccount登录Azure仅本地可用,其他用户遇认证失败求助
使用PowerShell 7.2.4、Az Module 12版本编写脚本,通过固定凭据调用Connect-AzAccount登录Azure并获取资源信息,本地运行正常,但其他用户执行时登录失败,执行Az命令弹出如下错误:
Get-AzVM: Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.Authentication failed against tenant . User interaction is required. This may be due to the conditional access policy settings such as multi-factor authentication (MFA). If you need to access subscriptions in that tenant, please rerun 'Connect-AzAccount' with additional parameter '-TenantId '.
逐行调试时,Connect-AzAccount步骤弹出警告:
WARNING: Unable to acquire token for tenant '' with error 'Authentication failed against tenant . User interaction is required. This may be due to the conditional access policy settings such as multi-factor authentication (MFA). If you need to access subscriptions in that tenant, please rerun 'Connect-AzAccount' with additional parameter '-TenantId <tenantID'.
已确认:其他用户PC以管理员模式运行、执行策略已设置,Az-context显示账号/租户/订阅信息正确;目标账号未启用MFA和条件访问策略,权限无问题。
脚本代码如下:
$USER = 'AnAccount@atenant.onmicrosoft.com' $PWORD = ConvertTo-SecureString -String 'Password' -AsPlainText -Force $Credential = New-Object -TypeName System.Management.Automation.PSCredential ($USER, $PWORD) Connect-AzAccount -TenantID '<ID here>' -subscription <SubID here> -Credential $Credential
原因1:其他用户设备未完成Azure AD注册/加入
- 解决步骤:
- 执行
dsregcmd /status,检查Device State下的AzureAdJoined或WorkplaceJoined状态,确认设备已加入Azure AD或注册为工作设备。 - 若设备未注册,先执行一次交互登录:
Connect-AzAccount -TenantID '<你的租户ID>' -Credential $Credential -DeviceCode,完成设备码验证后,再运行原脚本尝试自动登录。
- 执行
原因2:Az模块缓存的旧凭据或上下文冲突
- 解决步骤:
- 清理Az模块缓存:
Clear-AzContext -Force Clear-AzProfile -Force - 关闭所有PowerShell窗口,重新打开后执行原脚本。
- 清理Az模块缓存:
原因3:账号的Azure AD非交互登录限制
- 解决步骤:
- 在Azure AD门户查看该账号的用户设置,确认开启"允许使用用户名/密码进行非交互登录"(部分租户默认限制此类登录方式)。
- 查看账号的登录日志,筛选失败记录,根据具体错误代码(如
50126密码验证失败、50074需要设备注册)定位问题。
原因4:PowerShell执行环境的权限或路径异常
- 解决步骤:
- 尝试用普通用户权限而非管理员权限执行脚本(管理员上下文可能导致凭据存储异常)。
- 检查环境变量
AZURE_CONFIG_DIR,确认未被自定义修改,避免凭据缓存路径错误。
内容的提问来源于stack exchange,提问作者user3844416

