Getting Azure DevOps tokens via an ServicePrincipal

Bjego
2 min readApr 13, 2023

Microsoft released new possibilities to connect to Azure DevOps via ServicePrincipals from Azure in March 2023. This is an alternative connection method to the well known PATs. Those where designed to give personal access to Azure DevOps, but where often used by “ServiceAccounts” to accomplish this.

Microsofts Blog

We are using Terraform to create a serviceprincipal an alternative could be the Az Cli Docu.

az ad sp create-for-rbac --name demoSp

You need the following information about your ServicePrincipal:

  • ClientId / appId
  • ClientSecret / password
  • TenantId / tenant

After creating the ServicePrincipal you have to login to azure devops and give it the correct grants.

  • Add it as a “Basic” User with no access to your organisation.
  • Add it to the Permission [Organisation]\Project Collection Build Administrators
  • Add a new AgentPool “on-prem”
  • Add the permission “Administratrion” to [Organisation]\Project Collection Build Administrators

The initial code was posted in the Microsoft Docs and on Github

You only need the generated token from the ClientSecretCredential. Which is generated in this code

var credentials = new ClientSecretCredential(azureDevOpsOptions.TenantId, azureDevOpsOptions.ClientId, azureDevOpsOptions.ClientSecret);
var accessToken = await credentials.GetTokenAsync(new Azure.Core.TokenRequestContext(new[] { azureDevOpsAppScope }));
Console.WriteLine(accessToken.Token);

You should store this token in a secret store and refresh it often. In the Video from the Microsoft docs, they said the token is only vailid for 1 hour!

When you register your self hosted agent you can now simply use your generated token instead of the PAT to connect to azure devops.

Examples for self hosted agents can be found here for Docker or here for Windows

We’ve choosen the docker one.

Originally published at https://github.com.

--

--