Use personal access tokens

Azure DevOps Services | Azure DevOps Server 2022 - Azure DevOps Server 2019 | TFS 2018

You can use a personal access token (PAT) as an alternate password to authenticate into Azure DevOps. In this article, we show you how to create, use, modify, and revoke PATs for Azure DevOps.

The following video shows you how to create and use a PAT.

About PATs

A personal access token contains your security credentials for Azure DevOps. A PAT identifies you, your accessible organizations, and scopes of access. As such, they're as critical as passwords, so you should treat them the same way.

If you're working within Microsoft tools, then your Microsoft account (MSA) or Microsoft Entra ID is an acceptable and well-supported approach. But, if you're working with third-party tools that don't support Microsoft or Microsoft Entra accounts – or you don't want to provide your primary credentials to the tool – use PATs to limit your risk.

You can create and manage your PATs through one of the following ways:

To set up PATs for non-Microsoft tools, use Git credential managers or create them manually. We recommend that you review our authentication guidance to help you choose the correct authentication mechanism. For smaller projects that require a less robust solution, PATs are a simple alternative. Unless your users are using a credential manager, they have to enter their credentials each time.

Create a PAT

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

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

    Screenshot showing selection, Personal Access Tokens.

  3. Select + New Token.

    Screenshot showing selection, New Token.

  4. Name your token, select the organization where you want to use the token, and then set your token to automatically expire after a set number of days.

    Screenshot showing entry of basic token information.

  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.

    Screenshot showing selected scopes for a PAT.

    Note

    You may be restricted from creating full-scoped PATs. If so, your Azure DevOps Administrator in Microsoft Entra ID has enabled a policy which limits you to a specific custom defined set of scopes. For more information, see Manage PATs with policies/Restrict creation of full-scoped PATs. For a custom defined PAT, the required scope for accessing the Component Governance API, vso.governance, isn't selectable in the UI.

  6. When you're done, copy the token and store it in a secure location. For your security, it doesn't display again.

    Screenshot showing how to copy the token to your clipboard.

Warning

Treat and use a PAT like your password and keep it a secret.

  1. Sign in to your web portal (https://{server}:8080/tfs/).

  2. From your home page, open your profile. Go to your security details.

Screenshot showing home page, opening your profile, and the Security button.

  1. Create a personal access token.

Screenshot showing adding a personal access token.

  1. Name your token. Select a lifespan for your token.

    If you have more than one organization, you can also select the organization where you want to use the token.

    Screenshot showing information entry, including token name and lifespan.

  2. 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, limit your token's scope to Agent Pools (read, manage).

  3. When you're done, make sure to copy the token. For your security, it doesn't display again. Use this token as your password. Select Close.

    Screenshot showing created token.

Use your PAT anywhere your user credentials are required for authentication in Azure DevOps.

Important

For organizations backed by Microsoft Entra ID, you have 90 days to sign in with your new PAT, otherwise it's considered inactive. For more information, see User sign-in frequency for Conditional Access.

Notifications

Users receive two notifications during the lifetime of a PAT - one upon creation and the other seven days before the expiration.

After you create a PAT, you receive a notification similar to the following example. This notification confirms that your PAT was added to your organization.

Screenshot showing PAT created notification.

The following image shows an example of the seven-day notification before your PAT expires.

Screenshot showing PAT near expiration notification.

Unexpected notification

If you receive an unexpected PAT notification, an administrator or tool might have created a PAT on your behalf. See the following examples.

  • When you connect to an Azure DevOps Git repo through git.exe. it creates a token with a display name like "git: https://MyOrganization.visualstudio.com/ on MyMachine."
  • When you or an administrator sets up an Azure App Service web app deployment, it creates a token with a display name like "Service Hooks: : Azure App Service: : Deploy web app."
  • When you or an administrator sets up web load testing as part of a pipeline, it creates a token with a display name like "WebAppLoadTestCDIntToken."
  • When a Microsoft Teams Integration Messaging Extension is set up, it creates a token with a display name like "Microsoft Teams Integration."

Warning

If you believe that a PAT exists in error, we suggest you revoke the PAT. Then, change your password. As a Microsoft Entra user, check with your administrator to see if your organization was used from an unknown source or location. See also the FAQ about accidentally checking in a PAT to a public GitHub repository.

Use a PAT

Your PAT is your identity and represents you when you use it, just like a password.

Git

Git interactions require a username, which can be anything except the empty string. To use a PAT with HTTP basic authentication, use Base64-encode for and $MyPat, which is included in the following code block.

In PowerShell, enter the following code.

$MyPat = 'yourPAT'

$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("`:$MyPat"))

git -c http.extraHeader="Authorization: Basic $B64Pat" clone https://dev.azure.com/yourOrgName/yourProjectName/_git/yourRepoName


To keep your token more secure, use credential managers so you don't have to enter your credentials every time. We recommend Git Credential Manager. Git for Windows is required.

Existing repos

For existing repositories, if you already added the origin using the username, run the following command first.

git remote remove origin

Otherwise, run the following command.

git remote add origin https://<PAT>@<company_machineName>.visualstudio.com:/<path-to-git-repo> path to git repo = <project name>/_git/<repo_name> git push -u origin --all

Use a PAT in your code

You can use a PAT in your code.

If you wish to provide the PAT through an HTTP header, first convert it to a Base64 string. The following example shows how to convert to Base64 using C#.


Authorization: Basic BASE64_USERNAME_PAT_STRING

The resulting string can then be provided as an HTTP header in the following format.

The following sample uses the HttpClient class in C#.

public static async void GetBuilds()
{
    try
    {
        var personalaccesstoken = "PATFROMWEB";

        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 = client.GetAsync(
                        "https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.0").Result)
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Tip

When you're using variables, add a $ at the beginning of the string, like in the following example.

public static async void GetBuilds()
{
   try
  {
      var personalaccesstoken = "PATFROMWEB";

      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 = client.GetAsync(
                       $"https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.0").Result)
           {
               response.EnsureSuccessStatusCode();
               string responseBody = await response.Content.ReadAsStringAsync();
               Console.WriteLine(responseBody);
           }
       }
   }
   catch (Exception ex)
   {
       Console.WriteLine(ex.ToString());
   }
}

When your code is working, it's a good time to switch from basic auth to OAuth.

For more information and examples of how to use PATs, see the following articles:

If you enable IIS Basic Authentication, PATs aren't valid. For more information, see Using IIS Basic Authentication on-premises.

Modify a PAT

You can regenerate or extend a PAT, and modify its scope. After regeneration, the previous PAT is no longer authorized.

  1. From your home page, open your user settings, and then select Profile.

    Screenshot showing sequence of buttons to select to modify a PAT.

  2. Under Security, select Personal access tokens. Select the token you want to modify, and then Edit.

    Screenshot showing highlighted Edit button to modify PAT.

  3. Edit the token name, token expiration, or the scope of access that's associated with the token, and then select Save.

    Screenshot showing modified PAT.

Revoke a PAT

You can revoke a PAT at any time, for various reasons.

  1. From your home page, open your user settings, and then select Profile.

    Screenshot showing sequence of buttons to select, Team Services, Preview page, and revoke a PAT.

  2. Under Security, select Personal access tokens. Select the token for which you want to revoke access, and then select Revoke.

    Screenshot showing selection to revoke a single token or all tokens.

  3. Select Revoke in the confirmation dialog.

    Screenshot showing confirmation screen to revoke PAT.

FAQs

Q: What happens to a PAT if a user account is disabled?

A: Once a user's removed from Azure DevOps, the PAT is invalidated within 1 hour. If your organization is connected to Microsoft Entra ID, the PAT is also invalidated in Microsoft Entra ID, as it belongs to the user. We recommend that the user rotates their PAT to another user or service account to keep services running.

Q: Is there a way to renew a PAT via REST API?

A: Yes, there's a way to renew, manage, and create PATs using our PAT Lifecycle Management APIs. For more information, see Manage PATs using REST API and our FAQ.

Q: Can I use basic auth with all Azure DevOps REST APIs?

A: No. You can use basic auth with most Azure DevOps REST APIs, but organizations and profiles only support OAuth. For more information, see Manage PATs using REST API.

Q: What happens if I accidentally check my PAT into a public repository on GitHub?

A: Azure DevOps scans for PATs checked into public repositories on GitHub. When we find a leaked token, we immediately send a detailed email notification to the token owner and log an event to your Azure DevOps organization's audit log. Unless you disabled the Automatically revoke leaked personal access tokens policy, we immediately revoke the leaked PAT. We encourage affected users to mitigate immediately by revoking the leaked token and replacing it with a new token.

For more information, see Revoke leaked PATs automatically.

Q: Can I use a personal access token as an ApiKey to publish NuGet packages to an Azure Artifacts feed using the dotnet/nuget.exe command line?

A: No. Azure Artifacts doesn't support passing a personal access token as an ApiKey. When using a local development environment, we recommended installing the Azure Artifacts Credential Provider to authenticate with Azure Artifacts. For more information, see the following examples: dotnet, NuGet.exe. If you want to publish your packages using Azure Pipelines, use the NuGet Authenticate task to authenticate with your feed example.

Q: Why did my PAT stop working?

A: PAT authentication requires you to regularly sign into Azure DevOps using the full authentication flow. Once every 30 days is sufficient for many, but you may need to sign in more often than that depending upon your Microsoft Entra configuration. If your PAT stops working, first try signing into your organization, ensuring that you go through the full authentication prompt. If your PAT still doesn't work after that, check to see if your PAT has expired.