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

Rest 在Azure中获取访问令牌时用户名或密码不正确,rest,azure,jwt,access-token,azure-api-apps,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=pass

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

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>();
HttpClient clie=newhttpclient();
字符串标记端点=”https://login.microsoftonline.com/{directoryID}/oauth2/token”;
var body=“资源=https://analysis.windows.net/powerbi/api&client_id=clientID&grant_type=password&username=myADusername&password=myADpassword";
var stringContent=新的stringContent(body,Encoding.UTF8,“application/x-www-form-urlencoded”);
var result=wait clie.PostAsync(令牌端点,stringContent).ContinueWith((响应)=>
{
返回response.Result.Content.ReadAsStringAsync().Result;
});
JObject=JObject.Parse(结果);
var token=jobject[“access_token”].Value();

我正在使用我的Azure AD用户名和密码获取令牌。我在我的MVC应用程序中使用了相同的凭据
var credential=new UserPasswordCredential(用户名、密码)哪个工作正常。但是在这个.NETCore2.0应用程序中,它给了我一个错误,说授予无效。无效的用户名或密码。这些凭据与我用来获取令牌的凭据相同,授权类型设置为password。我所做的有什么问题吗?

根据我的测试,演示代码对我有效。如果可能,请尝试在Azure广告中创建新用户,并使用创建的用户再次进行测试。 用户名格式为
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;
测试结果:


您需要对值进行URL编码。您可以使用
FormUrlEncodedContent
而不是
StringContent
以更简单的方式完成所有工作。我尝试使用Postman,但它给出了相同的错误。我使用的用户名是我的广告用户名,格式为:xxx@domain.com而不是xxx@domain.onmicrosoft.com. 如果我使用前一种格式,我会得到相同的错误-无效凭据。但如果我使用后一个,我会得到一个错误,说这个应用程序必须添加到。。。目录我还想指出,当我在使用MVC应用程序时,我使用了相同的用户名和密码,并且它正常工作。