Search code examples
tfsazure-devopstfs-sdk

How to Login to VSTS programmatically


I have an automatic branching utility that does various operations. We have upgraded to VSTS and I am having trouble using the Tfs calls with the new server:

//login

NetworkCredential netCred = new NetworkCredential("emailAddress", password");

BasicAuthCredential basicCred = new BasicAuthCredential(netCred);

TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);

tfsCred.AllowInteractive = false;

TfsTeamProjectCollection tfsServer = new TfsTeamProjectCollection(new Uri("https://myco.visualstudio.com/mycoll"), tfsCred);

// get a local workspace

VersionControlServer sc = server.GetService(typeof(VersionControlServer)) as VersionControlServer;

... other code

and then boom! "You are not authorized to access https://myco.visualstudio.com/mycoll"

Is there some setting somewhere?

Should I try and use the REST API?

Am I calling something I shouldn't?

I've tried all sorts of formats for the URI, with :8080, with /tfs in the path to no avail!


Solution

  • You can use PAT (Personal Access Token) to access VSTS. Click on your profile in VSTS and go to security menu item. You can define a PAT in there. Keep the PAT saved as it will only be shown once.

    enter image description here

    Define the scope as per your needs enter image description here

    You can use the PAT to access TFS REST API as shown in following PowerShell sample. Using https://yourAccount.visualstudio.com or https://yourAccount.visualstudio.com/DefaultCollection for ColletionUri parameter is OK.

    param(
        [Parameter(Mandatory=$true)]
        [string] $token,
        [Parameter(Mandatory=$true)]
        [string] $collectionUri
    )
    
    
    
    $User=""
    
    # Base64-encodes the Personal Access Token (PAT) appropriately
    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $User,$token)));
    $header = @{Authorization=("Basic {0}" -f $base64AuthInfo)};
    
    $Uri = $collectionUri + '/_apis/projects?api-version=1.0'
    
    $projects = Invoke-RestMethod -Method Get -ContentType application/json -Uri $Uri -Headers $header

    You can find C# code samples here https://www.domstamand.com/accessing-tfs-2017-programmatically/