Gosfly
Gosfly

Reputation: 1300

Use git credential manager to fetch azure devops api instead of personal access token

I am trying to fetch git azure devops api to get information about repositories and branches in js.

In order to achieve that, I made a little application with the following code :

$(document).ready(function() {
    var personalToken = btoa(':'+'<personnalAccessToken>');

    fetch('https://dev.azure.com/<company>/<project>/_apis/git/repositories?api-version=5.1', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
          'Authorization': 'Basic '+ personalToken
        }
    }).then(function(response) {
        return response.json();
    }).then(function(repositories) {
        console.log("There are "+repositories.count+" repositories");
    }).catch(function(error) {
        console.log('Fetch error: ' + error.message);
    });

This code is working great but as you can see there is my personnalAccessToken writen directly inside the code... which is really bad...

When I am using git in command line, I don't have to specify any credential information because I use git credential manager for windows. Which means my personnalAccessToken is already stored, cached and automatically used everytime I use a git command, like clone, etc.

So, I would like my js code to use the same thing, I would like it to use my stored credentials automatically to fetch the api without being required to set my personnalAccessToken in code.

I have already searched for hours but can't find out if it is possible.

Upvotes: 0

Views: 730

Answers (2)

CorgiDev
CorgiDev

Reputation: 93

If you have the script set up in an Azure Runbook you can set it as an encrypted variable there and have it pull it from there before running rather than having it directly written into the code.

$encryptedPatVarName = "ADO_PAT"
$adoPat = Get-AutomationVariable -Name $encryptedPatVarName
$adoPatToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($adoPat)"))
$adoHeader = @{authorization = "Basic $adoPatToken"}

The above is the Powershell version of it. I have seen some people do it with other

Upvotes: 1

LoLance
LoLance

Reputation: 28086

I have already searched for hours but can't find out if it is possible.

Sorry but as I know it's impossible. The way you're calling the Rest API is similar to use Invoke-RestMethod to call rest api in Powershell. In both these two scenarios, the process will try to fetch PAT for authentication in current session/context and it won't even try to search the cache in Git Credential Manager.

You should distinguish the difference between accessing Azure Devops service via Rest API and by Code:

Rest API:

POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1

Request Body:

{
  "query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'Task' AND [State] <> 'Closed' AND [State] <> 'Removed' order by [Microsoft.VSTS.Common.Priority] asc, [System.CreatedDate] desc"
}

Corresponding Code in C#:

VssConnection connection = new VssConnection(new Uri(azureDevOpsOrganizationUrl), new VssClientCredentials());
            //create http client and query for resutls
WorkItemTrackingHttpClient witClient = connection.GetClient<WorkItemTrackingHttpClient>();
Wiql query = new Wiql() { Query = "SELECT [Id], [Title], [State] FROM workitems WHERE [Work Item Type] = 'Bug' AND [Assigned To] = @Me" };
WorkItemQueryResult queryResults = witClient.QueryByWiqlAsync(query).Result;

Maybe you can consider using a limited PAT, limit its scope to Code only:

enter image description here

I know there exists other Authentication mechanism :

For Interactive JavaScript project: ADALJS and Microsoft-supported Client Libraries.

You can give it a try but I'm not sure if it works for you since you're not using real Code way to access the Azure Devops Service... Hope it makes some help :)

Upvotes: 1

Related Questions