-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
160 lines (124 loc) · 6.69 KB
/
Program.cs
File metadata and controls
160 lines (124 loc) · 6.69 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using CommandLine;
using Microsoft.Graph;
using Microsoft.Identity.Client;
using Microsoft.Identity.Web;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ap_cli
{
internal partial class Program
{
static void Main(string[] args)
{
Parser.Default.ParseArguments<Options>(args)
.WithParsed<Options>(o =>
{
try
{
AuthenticationConfig config;
if (o.appsettings)
{
config = AuthenticationConfig.ReadFromJsonFile("appsettings.json");
}
else
{
config = AuthenticationConfig.ReadFromArgs(o);
}
bool isUsingClientSecret = IsAppUsingClientSecret(config);
IConfidentialClientApplication app;
if (isUsingClientSecret)
{
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithClientSecret(config.ClientSecret)
.WithAuthority(new Uri(config.Authority))
.Build();
}
else
{
ICertificateLoader certificateLoader = new DefaultCertificateLoader();
certificateLoader.LoadIfNeeded(config.Certificate);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
.WithCertificate(config.Certificate.Certificate)
.WithAuthority(new Uri(config.Authority))
.Build();
}
app.AddInMemoryTokenCache();
RunAsync(app, config, o.GroupId, o.CatalogDisplayName, o.AccessPackageName,o.ApproverUserId).GetAwaiter().GetResult();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ResetColor();
}
});
}
private static async Task RunAsync(IConfidentialClientApplication app, AuthenticationConfig config, string groupId, string spokeCatalogDisplayName, string accessPackageName, string approverUserId)
{
groupId= groupId.Trim('"');
approverUserId = approverUserId.Trim('"');
// With client credentials flows the scopes is ALWAYS of the shape "resource/.default", as the
// application permissions need to be set statically (in the portal or by PowerShell), and then granted by a tenant administrator.
string[] scopes = new string[] { $"{config.ApiUrl}.default" }; // Generates a scope -> "https://graph.microsoft.com/.default"
GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes);
AccessPackageCatalog spokeAccessPackageCatalog = await CatalogCreateIfNotExists(graphServiceClient, spokeCatalogDisplayName);
AccessPackage accessPackage = await AccessPackageCreateIfNotExists(graphServiceClient, accessPackageName, spokeAccessPackageCatalog);
CatalogResource accessPackageCatalogGroup = await GroupAddIfNotExist(graphServiceClient, groupId, spokeCatalogDisplayName, spokeAccessPackageCatalog);
await GroupRoleAddIfNotExist(graphServiceClient, accessPackage, accessPackageCatalogGroup, groupId);
await AccessPackagePolicyCreateIfNotExist(graphServiceClient, accessPackage.Id, accessPackage.DisplayName, approverUserId);
}
private static async Task<string> SendBetaHttpMessage(GraphServiceClient graphServiceClient, string url, string body, HttpMethod method)
{
using (var httpClient = new HttpClient())
using (HttpRequestMessage request = new HttpRequestMessage(method, url))
{
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
await graphServiceClient.AuthenticationProvider.AuthenticateRequestAsync(request);
var response = await httpClient.SendAsync(request);
var res = await response.Content.ReadAsStringAsync();
response.EnsureSuccessStatusCode();
return res;
}
}
private static GraphServiceClient GetAuthenticatedGraphClient(IConfidentialClientApplication app, string[] scopes)
{
GraphServiceClient graphServiceClient =
new GraphServiceClient("https://graph.microsoft.com/V1.0/", new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
AuthenticationResult result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
}));
return graphServiceClient;
}
/// <summary>
/// Checks if the sample is configured for using ClientSecret or Certificate. This method is just for the sake of this sample.
/// You won't need this verification in your production application since you will be authenticating in AAD using one mechanism only.
/// </summary>
/// <param name="config">Configuration from appsettings.json</param>
/// <returns></returns>
private static bool IsAppUsingClientSecret(AuthenticationConfig config)
{
string clientSecretPlaceholderValue = "[Enter here a client secret for your application]";
if (!String.IsNullOrWhiteSpace(config.ClientSecret) && config.ClientSecret != clientSecretPlaceholderValue)
{
return true;
}
else if (config.Certificate != null)
{
return false;
}
else
throw new Exception("You must choose between using client secret or certificate.");
}
}
}