【问题标题】:Incorrect username or password while getting Access Token in Azure在 Azure 中获取访问令牌时用户名或密码不正确
【发布时间】:2019-03-21 04:54:38
【问题描述】:

这是我获取访问令牌的代码:

HttpClient clie = new HttpClient();
    string tokenEndpoint = "https://login.microsoftonline.com/{directoryID}/oauth2/token";
    var body = "resource=https://analysis.windows.net/powerbi/api&client_id=clientID&grant_type=password&username=myADusername&password=myADpassword";
   var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");

 var result = await clie.PostAsync(tokenEndpoint, stringContent).ContinueWith<string>((response) =>
                {
                    return response.Result.Content.ReadAsStringAsync().Result;
                });

                JObject jobject = JObject.Parse(result);

                var token = jobject["access_token"].Value<string>();

我正在使用我的 Azure AD 用户名和密码来获取令牌。我在我的 MVC 应用程序 var credential = new UserPasswordCredential(Username,Password); 中使用了相同的凭据,效果很好。但是在这个 .NET core 2.0 应用程序中,它给了我一个错误,说无效授权。用户名或密码无效。这些是我用来获取令牌的相同凭据,授权类型设置为密码。我在做什么有什么问题?

【问题讨论】:

  • 您需要对这些值进行 URL 编码。您可以使用 FormUrlEncodedContent 而不是 StringContent 以更简单的方式完成所有操作。
  • 我尝试过使用 Postman,但它给了我同样的错误。

标签: rest azure jwt access-token azure-api-apps


【解决方案1】:

根据我的测试,演示代码对我有用。如果可能,请尝试在您的 Azure AD 中创建一个新用户,并使用创建的用户再次对其进行测试。 用户名格式为username@xxx.xxx

HttpClient clie = new HttpClient();
string tokenEndpoint = "https://login.microsoftonline.com/{tenantId}/oauth2/token";
var body = "resource=https://analysis.windows.net/powerbi/api&client_id={nativeAppClientId}&grant_type=password&username=username@xxxx.onmicrosoft.com&password=password";
var stringContent = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
string result =  clie.PostAsync(tokenEndpoint, stringContent).ContinueWith((response) =>
            {
                return response.Result.Content.ReadAsStringAsync().Result;
            }).Result;

测试结果:

【讨论】:

  • 我使用的用户名是我的 AD 用户名,格式为:xxx@domain.com 而不是 xxx@domain.onmicrosoft.com。如果我使用前一种格式,我会收到相同的错误 - 凭据无效。但是,如果我使用后者,我会收到一条错误消息,指出必须将此应用程序添加到 ... 目录。我还想指出,当我使用 MVC 应用程序时,我使用了相同的用户名和密码,并且它可以正常工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 2013-02-18
  • 2020-09-15
  • 2018-07-09
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多