在Azure中获取访问令牌时用户名或密码不正确

时间:2018-10-16 15:35:34

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

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

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应用程序中,它给我一个错误,提示无效授予。用户名或密码无效。这些与我用于获取令牌的凭据相同,授予类型设置为密码。我在做什么错了?

1 个答案:

答案 0 :(得分: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;

测试结果:

enter image description here