C# 执行使用个人访问令牌,但不使用Azure DevOps的AAD访问令牌
我有下面的代码,它以JSON格式从Azure DevOps存储库输出主分支统计数据,我正在捕获所需的输出。当我使用个人访问令牌时,身份验证工作,并从API返回结果 但是,当我尝试使用AAD中注册的应用程序生成访问令牌(已在API权限下为Azure DevOps启用了委派用户模拟)时,我能够生成访问令牌,然后在调用API时传递它,但它会返回 状态代码:203,原因短语:“非权威信息”,版本:1.1,内容:C# 执行使用个人访问令牌,但不使用Azure DevOps的AAD访问令牌,c#,azure-active-directory,access-token,azure-devops-rest-api,C#,Azure Active Directory,Access Token,Azure Devops Rest Api,我有下面的代码,它以JSON格式从Azure DevOps存储库输出主分支统计数据,我正在捕获所需的输出。当我使用个人访问令牌时,身份验证工作,并从API返回结果 但是,当我尝试使用AAD中注册的应用程序生成访问令牌(已在API权限下为Azure DevOps启用了委派用户模拟)时,我能够生成访问令牌,然后在调用API时传递它,但它会返回 状态代码:203,原因短语:“非权威信息”,版本:1.1,内容:System.Net.Http.StreamContent 公共静态异步任务GetBuilds
System.Net.Http.StreamContent
公共静态异步任务GetBuilds()
{
字符串url=“Azure开发操作API”;
var personalaccesstoken=“personalaccesscode”;
//var personalaccesstoken=token.GetYourTokenWithClientCredentialsFlow().Result;
字符串值=null;
使用(HttpClient=new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
client.DefaultRequestHeaders.Authorization=newauthenticationHeaderValue(“Bearer”,Convert.ToBase64String(ascienceoding.ASCII.GetBytes(string.Format(“{0}:{1},”,personalaccesstoken)));
使用(HttpResponseMessage response=wait client.GetAsync(url))
{
response.EnsureSuccessStatusCode();
string responseBody=wait response.Content.ReadAsStringAsync();
动态jsonObject=JsonConvert.DeserializeObject(ResponseBy);
value=jsonObject;
}
}
if(值!=null)
{
控制台写入线(值);
}
}
公共静态异步任务GetYourTokenWithClientCredentialsFlow()
{
字符串标记URL=$”https://login.microsoftonline.com/{租户ID}/oauth2/token”;
var tokenRequest=newhttprequestmessage(HttpMethod.Post,tokenUrl);
tokenRequest.Content=newformurlencodedcontent(新字典
{
[“授权类型”]=“客户端凭据”,
[“客户端id”]=“客户端id”,
[“客户机密”]=“客户机密”,
[“资源”]=”https://graph.microsoft.com/"
});
动态json;
动态令牌;
字符串访问令牌;
HttpClient=新的HttpClient();
var tokenResponse=client.sendaync(tokenRequest).Result;
json=wait-tokenResponse.Content.ReadAsStringAsync();
token=JsonConvert.DeserializeObject(json);
accessToken=token.access\u token;
返回accessToken;
}
尝试使用postman使用上面代码生成的访问令牌进行测试,得到如下屏幕截图
我在这里做错了什么以及如何解决问题?azure ad访问令牌是一个承载令牌。您不需要将其用作基本身份验证 请尝试使用以下代码:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetYourTokenWithClientCredentialsFlow().Result);
更新:
如果您想访问Azure Devops API,您的资源应该是“499b84ac-1321-427f-aa17-267ca6975798”。有关更多详细信息,请参阅我仍然得到相同的答复:-(您无法使用客户端凭据流。您需要以用户身份登录。请稍后检查我的更新。感谢提供详细信息。我将尝试此操作,但不确定授权部分在默认情况下如何授予许可。当前已添加应用程序的Azure devOps API权限。将向您发布。此按钮用于r admin为整个租户授予许可。由于DevOps API许可可以由用户自己同意,因此您可以使用交互式登录一次。这将仅为用户授予许可。太好了!我必须获得我的组织对管理许可的批准,这解决了我的问题。您在适当的指导下提供了最好的帮助这是任何人都能理解的,非常感谢你花时间和帮助。
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetYourTokenWithClientCredentialsFlow().Result);
class Program
{
static string azureDevOpsOrganizationUrl = "https://dev.azure.com/jack0503/"; //change to the URL of your Azure DevOps account; NOTE: This must use HTTPS
static string clientId = "0a1f****-****-****-****-a2a4****7f69"; //change to your app registration's Application ID
static string replyUri = "https://localhost/"; //change to your app registration's reply URI
static string azureDevOpsResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Constant value to target Azure DevOps. Do not change
static string tenant = "hanxia.onmicrosoft.com"; //your tenant ID or Name
static String GetTokenInteractively()
{
AuthenticationContext ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant); ;
IPlatformParameters promptBehavior = new PlatformParameters(PromptBehavior.Auto | PromptBehavior.SelectAccount);
AuthenticationResult result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, new Uri(replyUri), promptBehavior).Result;
return result.AccessToken;
}
static String GetToken()
{
AuthenticationContext ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant); ;
UserPasswordCredential upc = new UserPasswordCredential("jack@hanxia.onmicrosoft.com", "yourpassword");
AuthenticationResult result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, upc).Result;
return result.AccessToken;
}
static void Main(string[] args)
{
//string token = GetTokenInteractively();
string token = GetToken();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(azureDevOpsOrganizationUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = client.GetAsync("_apis/projects").Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine("\tSuccesful REST call");
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
Console.ReadLine();
}
}
}