Azure DevOps Rest API - Authentication

Introduction

This post will walk you through how you can authenticate to the Azure DevOps API, and will also provide resources where you can find out what APIs are available. In this series of posts, I will be creating a command line tool that can be used to demonstrate each of the APIs that I cover. The code for this tool is available on GitHub.

Installing the NuGet Package

First, let’s install the Microsoft.VisualStudio.Services.Client NuGet package. This NuGet package is a C# wrapper around the Azure DevOps Rest API, and will allow you to authenticate and access information from your Azure DevOps site.

You can install the package in a a number of different ways. If you are using Visual Studio, then you can install it through the Manage NuGet Packages menu option. Alternatively, you can install it through the Package Manager with this command:

Install-Package Microsoft.VisualStudio.Services.Client

Or through the .NET CLI with this command:

dotnet add package Microsoft.VisualStudio.Services.Client

Create a Personal Access Token

In order to authenticate to the Azure DevOps Rest API, you will first need to create a Personal Access Token. When you create your token, you can specify which organizations that it has access to, as well as the scopes that it will be available. You can also specify when the token will expire. This page will walk you through the steps you need to perform to create the token.

Authenticating

The following snippet of code can be used to authenticate. You will need to fill in two pieces of information.

First, you need the URL of your Azure DevOps organization.

Note: this is the URL for the organization, not the project. If you use the project URL, it will not be able to authenticate.

Second, you need the personal access token you created earlier.

When creating the credentials, you do not need to specify a user name, as the personal access token is all that is needed to authenticate.

var uri = new Uri("<your-organization-url>");
var credentials = new VssBasicCredential("","<your-personal-access-token>");
var connection = new VssConnection(uri, credentials);
await connection.ConnectAsync().ConfigureAwait(false);

Retrieving Identity Information

Once you have authenticated to Azure DevOps, you can start to pull information into your application. Let’s start with getting the identity of the user. That data is available via the AuthenticatedIdentity property on the VssConnection. For example, if you wanted to output the name of the authenticated user, you could use the following code.

Console.WriteLine(connection.AuthenticatedUser.DisplayName);

Access Rest APIs

To access areas of the Azure DevOps Rest API, you will need to get an instance of the client for that area. Your main entry point for this is the .GetClient<T>() method on the VssConnection class. You will need to install the Microsoft.TeamFoundationServer.Client NuGet package to get access to the different clients. For example, to access Git, you would use the GitHttpClient, using the snippet below.

var gitClient = connection.GetClient<GitHttpClient>();

I will be exploring some of these clients in future posts. If you are interested in what is available through the Rest API, you can see all of the APIs in the documentation from Microsoft.

Creating an Identity Command

To demonstrate the authentication, I am going to add the first command to the AzureDevOpsCLI command line tool. This command will take the URL and personal access token, and will display the ID and DisplayName of the user.

Here is the code for the command.

[Command("identity", Description = "Retrieve identity information from Azure DevOps.")]
public class IdentityCommand : ICommand
{
    [CommandOption("base-url", 'b',
        Description = "The base url of your Azure DevOps organization.",
        IsRequired = true,
        EnvironmentVariableName = "azdo-cli-base-url")]
    public string? BaseUrl { get; set; }

    [CommandOption("personal-access-token", 'p',
        Description = "The personal access token to authenticate to Azure DevOps.",
        IsRequired = true,
        EnvironmentVariableName = "azdo-cli-personal-access-token")]
    public string? PersonalAccessToken { get; set; }

    public async ValueTask ExecuteAsync(IConsole console)
    {
        var baseUrl = new Uri(BaseUrl ?? "");
        var credentials = new VssBasicCredential("", PersonalAccessToken);
        var connection = new VssConnection(baseUrl, credentials);
        var identity = connection.AuthenticatedIdentity;
        await console.Output.WriteLineAsync(
            $"ID: {identity.Id}").ConfigureAwait(false);
        await console.Output.WriteLineAsync(
            $"Name: {identity.DisplayName}").ConfigureAwait(false);
    }
}

Running the new identity command outputs the identity of my user.

Full Command Example

I can also set environment variables for the URL and personal access token so that I don’t have to specify them every time I run the command.

Environment Variable Example

Conclusion

This post has covered the basics of authenticating to Azure DevOps. Future posts will build on this to demonstrate what can be done through the Rest APIs.

No Comments