获取Azure DevOps REST API 5.1的访问令牌。

huangapple go评论72阅读模式
英文:

Retrieve Accesstoken for Azure DevOps REST API 5.1

问题

在我们的应用程序中,我们想要检索一个访问令牌。使用此令牌,我们想要执行Azure DevOps rest API 5.1的特定操作。

我尝试了Microsoft提供的OAuth2(https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops)和PAT的建议文档。但始终返回203响应作为结果。是否有人知道如何解决这个问题的方法?

英文:

In our app we want to retrieve an accesstoken. With this token we want to perform certain actions with Azure DevOps rest API 5.1.

I've tried the suggested documententation from Microsoft for OAuth2 (https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/oauth?view=azure-devops) and PAT's. This always gives back a 203 response as an result. Does somebody know a workaround for this issue?

答案1

得分: 2

根据我的测试,我们可以使用Azure AD访问令牌调用Azure DevOps的REST API。有关更多详细信息,请参考以下步骤:

  1. 注册一个Azure AD应用程序
    获取Azure DevOps REST API 5.1的访问令牌。

  2. 配置应用程序

    a. 创建客户端密钥

    b. 配置权限

    获取Azure DevOps REST API 5.1的访问令牌。

  3. 获取令牌

    # 获取代码
    GET  https://login.microsoftonline.com/{tenant}/oauth2/authorize?
    client_id=<您的应用程序客户端ID>
    &response_type=code
    &redirect_uri=<>
    &response_mode=query
    &resource=499b84ac-1321-427f-aa17-267ca6975798
    &state=12345
    
    # 获取令牌
    POST https://login.microsoftonline.com/{tenant}/oauth2/token
    Content-Type: application/x-www-form-urlencoded
    grant_type=authorization_code
    &client_id=<>
    &code=<>
    &redirect_uri=https%3A%2F%2Flocalhost%3A12345
    &resource=499b84ac-1321-427f-aa17-267ca6975798
    &client_secret=<>
    
  4. 调用REST API
    获取Azure DevOps REST API 5.1的访问令牌。

英文:

According to my test, we can call Azure DevOps rest API with Azure Ad access token. For more details, please refer to the following steps

  1. Register an Azure AD application
    获取Azure DevOps REST API 5.1的访问令牌。

  2. Configure applications

    a. Create client secret

    b. Configure permissions

    获取Azure DevOps REST API 5.1的访问令牌。

  3. Get token

     # get code
    

GET https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=<your app client id>
&response_type=code
&redirect_uri=<>
&response_mode=query
&resource=499b84ac-1321-427f-aa17-267ca6975798
&state=12345

#Get token
Post https://login.microsoftonline.com/{tenant}/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=<>
&code=<>
&redirect_uri=https%3A%2F%2Flocalhost%3A12345
&resource=499b84ac-1321-427f-aa17-267ca6975798
&client_secret=<>


4. Call Rest API
[![enter image description here][3]][3]


[1]: https://i.stack.imgur.com/waX3r.png
[2]: https://i.stack.imgur.com/29Rjk.png
[3]: https://i.stack.imgur.com/QbkQj.png

</details>



# 答案2
**得分**: 0

以下是已翻译的内容:

- 获取调用 API 的身份验证信息,请参考:[身份验证](https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1#authenticate)

- 这是使用 OAuth2 与 ADAL 的示例:[OAuth2 示例](https://github.com/microsoft/azure-devops-auth-samples/blob/master/ManagedClientConsoleAppSample/Program.cs)

- 这是使用 PAT 的快速示例:

```csharp
 class Program
 {
 	public static string personalaccesstoken = "erxvtg*****6aljqa";
 	public static string organization = "jack0503";
 	public static string project = "keyvault";

 	static void Main(string[] args)
 	{
 		Console.ReadLine();
 		GetProjects();
 		Console.ReadLine();
 	}

 	public static async void GetProjects()
 	{
 		try
 		{
 			using (HttpClient client = new HttpClient())
 			{
 				client.DefaultRequestHeaders.Accept.Add(
 					new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

 				client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
 					Convert.ToBase64String(
 						System.Text.ASCIIEncoding.ASCII.GetBytes(
 							string.Format("{0}:{1}", "", personalaccesstoken))));

 				using (HttpResponseMessage response = await client.GetAsync(
 							$"https://dev.azure.com/{organization}/_apis/projects"))
 				{
 					response.EnsureSuccessStatusCode();
 					string responseBody = await response.Content.ReadAsStringAsync();
 					Console.WriteLine(responseBody);
 				}
 			}
 		}
 		catch (Exception ex)
 		{
 			Console.WriteLine(ex.ToString());
 		}
 	}
 }

请注意,上述代码中的双引号 " 已被保留,没有进行翻译。

英文:

For how to get authenticated for calling API, you may refer to: Authenticate

Here is the sample for using OAuth2 with ADAL: https://github.com/microsoft/azure-devops-auth-samples/blob/master/ManagedClientConsoleAppSample/Program.cs

And here is a quick sample by using PAT:

	class Program
	{
		public static string personalaccesstoken = &quot;erxvtg*****6aljqa&quot;;
		public static string organization = &quot;jack0503&quot;;
		public static string project = &quot;keyvault&quot;;

		static void Main(string[] args)
		{
			Console.ReadLine();
			GetProjects();
			Console.ReadLine();
		}


		public static async void GetProjects()
		{
			try
			{
				using (HttpClient client = new HttpClient())
				{
					client.DefaultRequestHeaders.Accept.Add(
						new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));

					client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Basic&quot;,
						Convert.ToBase64String(
							System.Text.ASCIIEncoding.ASCII.GetBytes(
								string.Format(&quot;{0}:{1}&quot;, &quot;&quot;, personalaccesstoken))));

					using (HttpResponseMessage response = await client.GetAsync(
								$&quot;https://dev.azure.com/{organization}/_apis/projects&quot;))
					{
						response.EnsureSuccessStatusCode();
						string responseBody = await response.Content.ReadAsStringAsync();
						Console.WriteLine(responseBody);
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.ToString());
			}
		}
	}

huangapple
  • 本文由 发表于 2020年1月6日 17:29:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定