Reputation: 1298
Here's my code for getting the access token:
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>();
I am using my Azure AD username and password to get the token. I have used the same credentials in my MVC app var credential = new UserPasswordCredential(Username,Password);
which works fine. But in this .NET core 2.0 app it gives me an error saying invalid grant. Invalid username or password. These are the same credentials that I've used to get the token, the grant type is set to password. What is wrong with what I am doing?
Upvotes: 1
Views: 1529
Reputation: 24569
Based on my test, the demo code is working for me. If possible, please have a try to create a new user in the your Azure AD and use the created user to test it again.
username format is [email protected]
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&[email protected]&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;
Test Result:
Upvotes: 1