Acessing Azure DevOps By Using PAT

You may have come across a requirement, wherein you needed to update Azure DevOps objects programmatically and it is obvious that there must be some authentication mechanism which has to be in place.
 
Now, there are many methods one can use to authenticate, but for this post, I’ve specifically chosen personal access token. PAT, which is short for Personal Access Token is a way to provide an alternate password to authenticate to Azure DevOps.
 
To understand more about how to generate this token and how to utilize this, let’s follow certain steps and make a successful REST API call.
 

When to use Personal Access Token

 
PAT is usually used in a scenario when you want external applications to interact with Azure DevOps but you do not want to provide that application your primary Azure portal credentials due to security reasons. So, in this case, PAT can be used. So, here PAT is just an another password which can access only your Azure DevOps services.
 

Generating Personal Access Token

 
First step is to sign in to Azure DevOps, which will have the URL of format https://dev.azure.com/<organizationName> and go to Settings as shown below,
 
Acessing Azure DevOps by using PAT
 
On Settings page, under Security, select Personal access tokens. Once it is clicked, a page will open on right side with an option to create a new token as shown in the below screen shot,
 
Acessing Azure DevOps by using PAT
 
Click on New Token and a new dialog will come up as shown below, wherein the Name of the token has to be provided along with the Organization name,
 
 
One of the most important things in the  above dialog is the Scope. Based on the business needs, one can select the scope for which this PAT is generated.
 

Using Personal Access Token

 
Next we will be using this newly generated PAT to make a call to one of the REST APIs. So, let’s quickly create a new C# class in your project and name it as DevOpsConnectionManager. This class will hold the basic information, which is required to make a successful connection to Azure DevOps,
  1. public class DevOpsConnectionManager        
  2.     {        
  3.         private readonly string organizationName;        
  4.         private readonly string projectName;        
  5.         private readonly string userName;        
  6.         private readonly string personalToken;        
  7.         private readonly string baseUrl;        
  8.       
  9.         private DevOpsConnectionManager(string organizationName, string projectName, string userName, string personalToken)        
  10.         {        
  11.             this.organizationName= organizationName;        
  12.             this.projectName= projectName;        
  13.             this.userName = userName;        
  14.             this.personalToken= personalToken;        
  15.             this.baseUrl = $"https://dev.azure.com/{organization}/{project}/_apis/wit";        
  16.        }      
  17.     
  18.      public string BaseUrl      
  19.         {    
  20.             get    
  21.             {    
  22.                 return baseUrl;    
  23.             }    
  24.             private set { }    
  25.         }    
  26.     
  27.         public string Version { getset; } = "api-version=5.1";     
  28.         public HttpClient CreateHttpClient()  
  29.         {  
  30.             HttpClient httpClient = new HttpClient();  
  31.             httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));  
  32.             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", userName, personalToken))););  
  33.             return httpClient;  
  34.         }   
  35. }     
Now the caller code, which is going to utilize our connection manager class to create an instance and finally make a call to the API. Here is the snippet for that,
  1. public async Task UpdateInformation(string id, List<WorkItemParameter> parameters)  
  2.         {  
  3.             var connection = new DevOpsConnectionManager(organizationName,projectName,userName,personalToken);
  4.             using(var client = connection.CreateHttpClient())  
  5.             {  
  6.                 var urlForWorkItem = $"{connection.BaseUrl}/workitems/{id}?{connection.Version}";  
  7.                 var content = JsonConvert.SerializeObject(parameters);  
  8.                 HttpContent content = new StringContent(content, Encoding.UTF8,  
  9.                                     "application/json-patch+json");  
  10.                 var response = await client.PatchAsync(urlForWorkItem, content);  
  11.             }  
  12.         }  
And that’s all for today. Hope you enjoyed this. Happy learning!
 
References