-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
84 lines (75 loc) · 3.16 KB
/
Program.cs
File metadata and controls
84 lines (75 loc) · 3.16 KB
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
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.WebApi;
namespace AzureFeedAuthenticationDemo
{
internal class Program
{
internal const string VssAuthorizationEndpoint = "X-VSS-AuthorizationEndpoint";
internal static bool IsValidAzureFeed(Uri uri)
{
// TODO: Add more valid hosts here
return uri.Host.Equals("pkgs.dev.azure.com", StringComparison.OrdinalIgnoreCase);
}
internal static async Task<HttpResponseHeaders> GetResponseHeadersAsync(Uri uri, CancellationToken cancellationToken)
{
using (HttpClient httpClient = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri))
{
using (var response = await httpClient.SendAsync(request, cancellationToken))
return response.Headers;
}
}
}
internal static async Task<Uri> GetAuthorizationEndpointAsync(Uri uri, CancellationToken cancellationToken)
{
var headers = await GetResponseHeadersAsync(uri, cancellationToken);
try
{
foreach (var endpoint in headers.GetValues(VssAuthorizationEndpoint))
{
if (Uri.TryCreate(endpoint, UriKind.Absolute, out var parsedEndpoint))
{
return parsedEndpoint;
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
return null;
}
internal static async Task<string> LoadFeedIndexAsync(Uri azureFeedUri, CancellationToken cancellationToken)
{
if (!IsValidAzureFeed(azureFeedUri))
{
throw new ArgumentException("Invalid Feed Url");
}
Uri baseUri = await GetAuthorizationEndpointAsync(azureFeedUri, cancellationToken) ?? throw new ArgumentException($"No authorization endpoint found for {azureFeedUri}");
//Prompt user for credential
using (VssConnection connection = new VssConnection(baseUri, new VssClientCredentials()))
{
await connection.ConnectAsync(cancellationToken);
using (HttpClient client = new HttpClient(connection.InnerHandler, disposeHandler: false))
{
var resp = await client.GetAsync(azureFeedUri, cancellationToken);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadAsStringAsync();
}
}
}
static void Main(string[] args)
{
string azureFeedUrl = args[0];
Uri azureFeedUri = new Uri(azureFeedUrl);
var indexJson = LoadFeedIndexAsync(azureFeedUri, CancellationToken.None).Result;
Console.WriteLine(indexJson);
}
}
}