forked from binarythistle/Secure-Daemon-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
79 lines (70 loc) · 2.85 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
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using System.Net.Http.Headers;
using System.Linq;
using System.Net.Http;
namespace CommandAPIClient
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Making the call...");
RunAsync().GetAwaiter().GetResult();
}
private static async Task RunAsync()
{
AuthConfig config = AuthConfig.ReadFromJsonFile("appsettings.json");
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
string[] ResourceIds = new string[] { config.ResourceID };
AuthenticationResult result = null;
try
{
result = await app.AcquireTokenForClient(ResourceIds).ExecuteAsync();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Token acquired \n");
Console.WriteLine(result.AccessToken);
Console.ResetColor();
}
catch (MsalClientException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
if (!string.IsNullOrEmpty(result.AccessToken))
{
var httpClient = new HttpClient();
var defaultRequestHeaders = httpClient.DefaultRequestHeaders;
if (defaultRequestHeaders.Accept == null ||
!defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
httpClient.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
}
defaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("bearer", result.AccessToken);
HttpResponseMessage response = await httpClient.GetAsync(config.BaseAddress);
if (response.IsSuccessStatusCode)
{
Console.ForegroundColor = ConsoleColor.Green;
string json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed to call the Web Api: {response.StatusCode}");
string content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Content: {content}");
}
Console.ResetColor();
}
}
}
}