我正在Dotnet Core中创建API,该API获取访问令牌并基于带有Power BI报告的实施。我创建了App Registration,它是Azure上的网络应用程序。我想用grant_type = password
方法实现令牌功能。
using (var client = new HttpClient())
{
var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("resource", AppSettings.resourceUrl),
new KeyValuePair<string, string>("client_id", AppSettings.clientId),
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", AppSettings.pbiUsername),
new KeyValuePair<string, string>("password", AppSettings.pbiPassword),
new KeyValuePair<string, string>("scope", "openid")})
);
var content = await result.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OAuthResult>(content);
}
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_secret", Appsettings.ClientSecret),
new KeyValuePair<string, string>("client_id", AppSettings.clientId),
new KeyValuePair<string, string>("resource", AppSettings.resourceUrl),
new KeyValuePair<string, string>("username", AppSettings.pbiUsername),
new KeyValuePair<string, string>("resource", AppSettings.pbiPassword)
});
var tenantName = AppSettings.tenantName;
accessToken =
await client.PostAsync("https://login.microsoftonline.com/common/oauth2/authorize", content)
.ContinueWith<string>((response) =>
{
AzureAdTokenResponse tokenRes =
JsonConvert.DeserializeObject<AzureAdTokenResponse>(response.Result.Content.ReadAsStringAsync()
.Result);
return tokenRes?.AccessToken;
});
}
我希望使用上述方法返回令牌。
答案 0 :(得分:0)
端点不正确,您应该使用https://login.microsoftonline.com/common/oauth2/token
。另外,您错过了KeyValuePair中的password
参数和重复的resource
参数。
请求如下:
响应:
代码:(您需要Json转换结果)
public static string passwordGetToken()
{
var client = new HttpClient();
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("client_id", ""),
new KeyValuePair<string, string>("resource", "https://analysis.windows.net/powerbi/api"),
new KeyValuePair<string, string>("username", ""),
new KeyValuePair<string, string>("password", "")
});
var response =
client.PostAsync("https://login.microsoftonline.com/common/oauth2/token", content).Result;
return response.Content.ReadAsStringAsync().Result;
}