首页 > 解决方案 > 如何在 C# 中重现 powershell > az login 的结果?

问题描述

“az login”的结果是订阅列表:像这里: https ://docs.microsoft.com/en-us/rest/api/resources/subscriptions/list?source=docs

如何在不提供tenantId 或clientId 的情况下为该请求制作令牌,而这正是它在网站登录时的制作方式?

我可以使令牌非常接近要求,但没有我在网站上看到的令牌:

var functionCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(clientId, secret);
var context = new AuthenticationContext("https://login.microsoftonline.com/" + tenantId, false);
var result = context.AcquireTokenAsync("https://management.core.windows.net/", functionCred).Result;
var token44 = result.AccessToken;

我应该怎么做才能改进令牌?

标签: c#azureauthenticationcommand-line-interface

解决方案


默认情况下,az login命令使用用户帐户登录。CLI 将尝试启动 Web 浏览器以交互方式登录,如果浏览器不可用,则 CLI 将回退到设备代码登录。

对于这个问题 -

如何在不提供tenantId 或clientId 的情况下为该请求制作令牌,而这正是它在网站登录时的制作方式?

不使用tenantId 和clientId 获取身份验证令牌是不可行的。令牌主要由客户端 ID 和机密生成。Token可以通过app注册+tenentId或者用户凭证+tenentId获取。

下面的代码片段显示了如何使用 Azure Active Directory 身份验证库 (ADAL) 获取访问令牌。

static AuthenticationResult AccessToken() 
{ 
    string resourceUri = "https://datacatalog.azure.com";

    // register a client app and get a Client ID
    string clientId = clientIDFromAzureAppRegistration; 

    //A redirect uri gives AAD more details about the specific application that it will authenticate. 
    string redirectUri = "https://login.live.com/oauth20_desktop.srf"; 

    // Create an instance of AuthenticationContext to acquire an Azure access token 
    string authorityUri = "https://login.windows.net/common/oauth2/authorize";

    AuthenticationContext authContext = new AuthenticationContext(authorityUri); 

    // AcquireToken takes a Client Id that Azure AD creates when you register your client app. 
    return authContext.AcquireToken(resourceUri, clientId, new Uri(redirectUri), PromptBehavior.RefreshSession); 

}

有关更多信息,请查看此步骤以获取Microsoft 文档的访问令牌部分。


推荐阅读