Search code examples
c#.nettfsazure-devopsbasic-authentication

How to authenticate to Visual Studio Team Services with the new basic authentication from a .Net Windows Service?


I am trying to access https://visualstudio.com (formerly known as https://tfs.visualstudio.com, http://www.tfspreview.com) from my Windows Service written on .NET.

I want to use the new basic authentication but I couldn't find a way to do it.

I found a lot of links to the blog post Team Foundation Service updates - Aug 27 but it is using the Team Explorer Everywhere Java client for TFS.

Is there a new version of the TFS .NET Object Model to support the basic authentication?

By the way I've successively logged in with the service account. This answer was very useful.


Solution

  • First of all, you need to have at least Visual Studio 2012 Update 1 installed on your machine. It includes an updated Microsoft.TeamFoundation.Client.dll assembly with the BasicAuthCredential class.

    Here's the code to do it, from Buck's blog post How to connect to Team Foundation Service.

    using System;
    using System.Net;
    using Microsoft.TeamFoundation.Client;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                NetworkCredential netCred = new NetworkCredential(
                    "[email protected]",
                    "yourbasicauthpassword");
                BasicAuthCredential basicCred = new BasicAuthCredential(netCred);
                TfsClientCredentials tfsCred = new TfsClientCredentials(basicCred);
                tfsCred.AllowInteractive = false;
    
                TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(
                    new Uri("https://YourAccountName.visualstudio.com/DefaultCollection"),
                    tfsCred);
    
                tpc.Authenticate();
    
                Console.WriteLine(tpc.InstanceId);
            }
        }
    }