VisualStudioCredential认证异常与AzurePowerShellCredential行为差异咨询
我在使用DefaultAzureCredential进行认证时遇到问题,执行以下代码:
var credentials = new VisualStudioCredential(); var context = new TokenRequestContext(scopes: new string[] { _storageAccountUrl + "/.default" }); var token = await credentials.GetTokenAsync(context, new System.Threading.CancellationToken());
出现如下错误:
TS003: Error, TS004: Unable to get access token. 'AADSTS50020: User account '{EmailHidden}' from identity provider 'live.com' does not exist in tenant 'Microsoft Services' and cannot access the application '04f0c124-f2bc-4f59-8241-bf6df9866bbd'(VS with native MSA) in that tenant. The account needs to be added as an external user in the tenant first. Sign out and sign in again with a different Azure Active Directory user account.
但将凭证改为以下代码则可以正常运行:
var credentials = new AzurePowerShellCredential();
我在Visual Studio和PowerShell中登录的是同一用户,有人知道这是为什么吗?
- 更新 -
感谢@Juunas,使用以下代码可以正常运行,但为何VisualStudioCredential需要这样设置,而PowerShell却不需要?
var options = new VisualStudioCredentialOptions() { TenantId = "TENANT-ID-HERE" }; var credentials = new VisualStudioCredential(options);
原因分析
VisualStudioCredential的默认逻辑:
VisualStudioCredential默认会向"Microsoft Services"这个公共租户请求令牌,而你的MSA账号(live.com身份提供商)并不属于该租户,因此触发了AADSTS50020错误。必须显式指定目标资源所在的租户ID,才能让它向正确的租户发起认证请求。AzurePowerShellCredential的默认逻辑:
AzurePowerShell在登录时会将会话与你指定的租户绑定(比如首次登录选择的租户,或通过Set-AzContext切换的租户),AzurePowerShellCredential会直接复用这个已绑定的租户上下文,因此无需额外指定TenantId就能获取对应租户的令牌。
本质上两者的差异在于默认租户的获取逻辑:VisualStudioCredential默认走公共租户,而AzurePowerShellCredential复用PowerShell会话中已有的租户信息。
内容的提问来源于stack exchange,提问作者Donny Kwitty

