-
Notifications
You must be signed in to change notification settings - Fork 308
/
Program.cs
121 lines (108 loc) · 5.13 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
using Microsoft.Identity.Client;
using System;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace ManagedClientConsoleAppSample
{
class Program
{
//
// The Client ID is used by the application to uniquely identify itself to Azure AD.
// The Tenant is the name or Id of the Azure AD tenant in which this application is registered.
// The AAD Instance is the instance of Azure, for example public Azure or Azure China.
// The Authority is the sign-in URL of the tenant.
//
internal static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
internal static string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
internal static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
internal static string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
//URL of your Azure DevOps account.
internal static string azureDevOpsOrganizationUrl = ConfigurationManager.AppSettings["ado:OrganizationUrl"];
internal static string[] scopes = new string[] { "499b84ac-1321-427f-aa17-267ca6975798/user_impersonation" }; //Constant value to target Azure DevOps. Do not change
// MSAL Public client app
private static IPublicClientApplication application;
public static async Task Main(string[] args)
{
try
{
var authResult = await SignInUserAndGetTokenUsingMSAL(scopes);
// Create authorization header of the form "Bearer {AccessToken}"
var authHeader = authResult.CreateAuthorizationHeader();
ListProjects(authHeader);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Something went wrong.");
Console.WriteLine("Message: " + ex.Message + "\n");
}
Console.ReadLine();
}
/// <summary>
/// Sign-in user using MSAL and obtain an access token for Azure DevOps
/// </summary>
/// <param name="scopes"></param>
/// <returns>AuthenticationResult</returns>
private static async Task<AuthenticationResult> SignInUserAndGetTokenUsingMSAL(string[] scopes)
{
// Initialize the MSAL library by building a public client application
application = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithDefaultRedirectUri()
.Build();
AuthenticationResult result;
try
{
var accounts = await application.GetAccountsAsync();
result = await application.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// If the token has expired, prompt the user with a login prompt
result = await application.AcquireTokenInteractive(scopes)
.WithClaims(ex.Claims)
.ExecuteAsync();
}
return result;
}
/// <summary>
/// Get all projects in the organization that the authenticated user has access to and print the results.
/// </summary>
/// <param name="authHeader"></param>
private static void ListProjects(string authHeader)
{
// use the httpclient
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(azureDevOpsOrganizationUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("User-Agent", "ManagedClientConsoleAppSample");
client.DefaultRequestHeaders.Add("X-TFS-FedAuthRedirect", "Suppress");
client.DefaultRequestHeaders.Add("Authorization", authHeader);
// connect to the REST endpoint
HttpResponseMessage response = client.GetAsync("_apis/projects?stateFilter=All&api-version=2.2").Result;
// check to see if we have a succesfull respond
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Succesful REST call");
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
}
else if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
throw new UnauthorizedAccessException();
}
else
{
Console.WriteLine("{0}:{1}", response.StatusCode, response.ReasonPhrase);
}
}
}
}
}