Vinny
Vinny

Reputation: 629

How to get Authentication Token to get VSO Workitems using C#

I have a requirement to Get VSO workitem using C# Rest API call. I'm unable to figure out how to get the token for my http request. Below is what I have. Can someone give me the code to get the token to authenticate to VSO.

https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/get%20work%20item?view=azure-devops-rest-6.0

using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace GetVSOTask
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string token = "?????";           
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://dev.azure.com/")
            };
            string URI = $"Microsoft/OSGS/_apis/wit/workitems/31054512?&api-version=6.0";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
            var HttpsResponse = await response.Content.ReadAsStringAsync();

            Console.WriteLine(HttpsResponse);

            Console.ReadLine();
        }
    }
}

Upvotes: 3

Views: 1299

Answers (2)

Kevin Lu-MSFT
Kevin Lu-MSFT

Reputation: 35184

To pass the PAT Token to the C# HTTP header, you need to convert it to a Base64 string.

string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", "PAT")));

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

Here is an example:

       ...

        {
            string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", "PAT")));
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri($"https://dev.azure.com/{OrganizationName}");  //url of your organization
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                //connect to the REST endpoint            
                HttpResponseMessage response = client.GetAsync("/ProjectName/_apis/wit/workitems/467?api-version=6.0").Result;

                //check to see if we have a successful response
                if (response.IsSuccessStatusCode)
                {
                    var value = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(value);
                    Console.ReadLine();
                }


            }
        }

For more detailed information, you could refer to this doc or Get started with the REST APIs.

Upvotes: 2

Shayki Abramczyk
Shayki Abramczyk

Reputation: 41545

You need to generate the token in Azure DevOps portal:

  1. Sign in to your organization in Azure DevOps (https://dev.azure.com/{yourorganization})

  2. From your home page, open your user settings, and then select Personal access tokens.

  3. And then select + New Token.

  4. Name your token, select the organization where you want to use the token, and then choose a lifespan for your token.

  5. Select the scopes for this token to authorize for your specific tasks.

For example, to create a token to enable a build and release agent to authenticate to Azure DevOps Services, limit your token's scope to Agent Pools (Read & manage). To read audit log events, and manage and delete streams, select Read Audit Log, and then select Create.

  1. When you're done, make sure to copy the token. For your security, it won't be shown again. Use this token as your password.

Once your PAT is created, you can use it anywhere your user credentials are required for authentication in Azure DevOps.

See here more info.

Upvotes: 0

Related Questions