【发布时间】:2020-01-04 17:59:42
【问题描述】:
我的以下代码以 JSON 格式从 Azure DevOps 存储库输出主分支统计信息,我正在捕获所需的输出。这在我使用个人访问令牌时起作用,身份验证起作用并从 API 中返回结果。
但是当我尝试使用 AAD 中的注册应用程序生成访问令牌时(在 API 权限下为 Azure DevOps 启用了委派用户模拟),我能够生成访问令牌,然后在调用 API 时传递它,但是它返回
StatusCode:203,ReasonPhrase:“非权威信息”,版本:1.1,内容:
System.Net.Http.StreamContent
public static async Task GetBuilds()
{
string url = "Azure Dev-Ops API";
var personalaccesstoken = "personalaccesscode";
//var personalaccesstoken = token.GetYourTokenWithClientCredentialsFlow().Result;
string value = null;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(url))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
dynamic jsonObject = JsonConvert.DeserializeObject(responseBody);
value = jsonObject;
}
}
if (value != null)
{
Console.WriteLine(value);
}
}
public static async Task<string> GetYourTokenWithClientCredentialsFlow()
{
string tokenUrl = $"https://login.microsoftonline.com/{tenant ID}/oauth2/token";
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
["grant_type"] = "client_credentials",
["client_id"] = "client ID",
["client_secret"] = "client secret",
["resource"] = "https://graph.microsoft.com/"
});
dynamic json;
dynamic token;
string accessToken;
HttpClient client = new HttpClient();
var tokenResponse = client.SendAsync(tokenRequest).Result;
json = await tokenResponse.Content.ReadAsStringAsync();
token = JsonConvert.DeserializeObject(json);
accessToken = token.access_token;
return accessToken;
}
使用上面代码生成的访问令牌尝试使用邮递员进行测试,得到如下截图。
我在这里做错了什么,我该如何解决这个问题?
【问题讨论】:
-
如果你想访问 Azure Devops API,你的资源应该是“499b84ac-1321-427f-aa17-267ca6975798”。更多详情请参考github.com/microsoft/azure-devops-auth-samples/tree/master/…
标签: c# azure-active-directory access-token azure-devops-rest-api