|
| 1 | +using Microsoft.IdentityModel.Clients.ActiveDirectory; |
| 2 | +using System; |
| 3 | +using System.Linq; |
| 4 | +using System.Net.Http; |
| 5 | +using System.Net.Http.Headers; |
| 6 | +using System.Text.RegularExpressions; |
| 7 | +using Microsoft.VisualStudio.Services.Client; |
| 8 | +using Microsoft.VisualStudio.Services.WebApi; |
| 9 | +using Microsoft.TeamFoundation.Core.WebApi; |
| 10 | +using System.Collections.Generic; |
| 11 | + |
| 12 | +namespace VstsTfsSample |
| 13 | +{ |
| 14 | + class Program |
| 15 | + { |
| 16 | + //============= Config [Edit these with your settings] ===================== |
| 17 | + internal const string vstsOrTfsCollectionUrl = "https://myaccount.visualstudio.com"; //change to the URL of your VSTS or TFS account |
| 18 | + internal const string clientId = "0fa17cf4-f75c-4185-ab9a-7c5ea47ca073"; //change to your app registration's Application ID (For VSTS ADAL authentication) |
| 19 | + internal const string replyUri = "http://adalsample"; //change to your app registration's reply URI. (For VSTS ADAL authentication) |
| 20 | + //========================================================================== |
| 21 | + |
| 22 | + internal const string VSTSResourceId = "499b84ac-1321-427f-aa17-267ca6975798"; //Constant value to target VSTS. Do not change |
| 23 | + |
| 24 | + public static void Main(string[] args) |
| 25 | + { |
| 26 | + //Decipher VSTS or TFS collection |
| 27 | + if (isVsts(vstsOrTfsCollectionUrl)) |
| 28 | + { |
| 29 | + //VSTS ADAL authentication |
| 30 | + AuthenticationContext ctx = GetAuthenticationContext(null); |
| 31 | + AuthenticationResult result = null; |
| 32 | + try |
| 33 | + { |
| 34 | + //PromptBehavior.RefreshSession will enforce an authn prompt every time. NOTE: Auto will take your windows login state if possible |
| 35 | + result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Always)).Result; |
| 36 | + Console.WriteLine("Token expires on: " + result.ExpiresOn); |
| 37 | + |
| 38 | + var bearerAuthHeader = new AuthenticationHeaderValue("Bearer", result.AccessToken); |
| 39 | + //using access token to call REST endpoint |
| 40 | + ListProjects(bearerAuthHeader); |
| 41 | + } |
| 42 | + catch (UnauthorizedAccessException) |
| 43 | + { |
| 44 | + // If the token has expired, prompt the user with a login prompt |
| 45 | + result = ctx.AcquireTokenAsync(VSTSResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Always)).Result; |
| 46 | + } |
| 47 | + catch (Exception ex) |
| 48 | + { |
| 49 | + Console.WriteLine("{0}: {1}", ex.GetType(), ex.Message); |
| 50 | + } |
| 51 | + } else |
| 52 | + { |
| 53 | + //TFS Windows credential authentication |
| 54 | + VssConnection connection = new VssConnection(new Uri(vstsOrTfsCollectionUrl), new VssClientCredentials()); |
| 55 | + |
| 56 | + ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>(); |
| 57 | + IEnumerable<TeamProjectReference> projects = projectClient.GetProjects().Result; |
| 58 | + foreach (TeamProjectReference p in projects) |
| 59 | + { |
| 60 | + Console.WriteLine(p.Name); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + private static bool isVsts(string collectionUrl) |
| 66 | + { |
| 67 | + string regexPattern = @"\w+(.visualstudio.com)"; |
| 68 | + Match m = Regex.Match(collectionUrl, regexPattern); |
| 69 | + return m.Success; |
| 70 | + } |
| 71 | + |
| 72 | + private static AuthenticationContext GetAuthenticationContext(string tenant) |
| 73 | + { |
| 74 | + AuthenticationContext ctx = null; |
| 75 | + if (tenant != null) |
| 76 | + ctx = new AuthenticationContext("https://login.microsoftonline.com/" + tenant); |
| 77 | + else |
| 78 | + { |
| 79 | + ctx = new AuthenticationContext("https://login.windows.net/common"); |
| 80 | + if (ctx.TokenCache.Count > 0) |
| 81 | + { |
| 82 | + string homeTenant = ctx.TokenCache.ReadItems().First().TenantId; |
| 83 | + ctx = new AuthenticationContext("https://login.microsoftonline.com/" + homeTenant); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + return ctx; |
| 88 | + } |
| 89 | + |
| 90 | + private static void ListProjects(AuthenticationHeaderValue authHeader) |
| 91 | + { |
| 92 | + // use the httpclient |
| 93 | + using (var client = new HttpClient()) |
| 94 | + { |
| 95 | + client.BaseAddress = new Uri(vstsOrTfsCollectionUrl); |
| 96 | + client.DefaultRequestHeaders.Accept.Clear(); |
| 97 | + client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); |
| 98 | + client.DefaultRequestHeaders.Add("User-Agent", "ManagedClientConsoleAppSample"); |
| 99 | + client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress"); |
| 100 | + client.DefaultRequestHeaders.Authorization = authHeader; |
| 101 | + |
| 102 | + // connect to the REST endpoint |
| 103 | + HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result; |
| 104 | + |
| 105 | + // check to see if we have a succesfull respond |
| 106 | + if (response.IsSuccessStatusCode) |
| 107 | + { |
| 108 | + Console.WriteLine("\tSuccesful REST call"); |
| 109 | + Console.WriteLine(response.Content.ReadAsStringAsync().Result); |
| 110 | + } |
| 111 | + else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) |
| 112 | + { |
| 113 | + throw new UnauthorizedAccessException(); |
| 114 | + } |
| 115 | + else |
| 116 | + { |
| 117 | + Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase); |
| 118 | + } |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | +} |
0 commit comments