-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathAuthenticationHelpers.cs
504 lines (455 loc) · 26.4 KB
/
AuthenticationHelpers.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
using Azure.Core;
using Azure.Core.Diagnostics;
using Azure.Core.Pipeline;
using Azure.Identity;
using Azure.Identity.Broker;
using Microsoft.Graph.Authentication;
using Microsoft.Graph.PowerShell.Authentication.Core.Extensions;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Extensions.Msal;
using System;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Graph.PowerShell.Authentication.Core.Utilities
{
/// <summary>
/// Helper class for authentication.
/// </summary>
public static class AuthenticationHelpers
{
/// <summary>
/// Gets a <see cref="TokenCredential"/> using the provide <see cref="IAuthContext"/>.
/// </summary>
/// <param name="authContext">The <see cref="IAuthContext"/> to get a token credential for.</param>
/// <returns>A <see cref="TokenCredential"/> based on provided <see cref="IAuthContext"/>.</returns>
public static async Task<TokenCredential> GetTokenCredentialAsync(IAuthContext authContext, CancellationToken cancellationToken = default)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
switch (authContext.AuthType)
{
case AuthenticationType.Delegated:
if (authContext.TokenCredentialType == TokenCredentialType.InteractiveBrowser)
return await GetInteractiveBrowserCredentialAsync(authContext, cancellationToken).ConfigureAwait(false);
return await GetDeviceCodeCredentialAsync(authContext, cancellationToken).ConfigureAwait(false);
case AuthenticationType.AppOnly:
return authContext.TokenCredentialType == TokenCredentialType.ClientCertificate
? await GetClientCertificateCredentialAsync(authContext).ConfigureAwait(false)
: await GetClientSecretCredentialAsync(authContext).ConfigureAwait(false);
case AuthenticationType.ManagedIdentity:
return await GetManagedIdentityCredentialAsync(authContext).ConfigureAwait(false);
case AuthenticationType.EnvironmentVariable:
return await GetEnvironmentCredentialAsync(authContext).ConfigureAwait(false);
case AuthenticationType.UserProvidedAccessToken:
return new UserProvidedTokenCredential();
default:
throw new NotSupportedException($"{authContext.AuthType} is not supported.");
}
}
private static async Task<TokenCredential> GetEnvironmentCredentialAsync(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
//There is need for explicitly adding TenantId to the TokenCredentialOptions for EnvironmentCredential due to stricter security requirements.
authContext.TenantId = EnvironmentVariables.TenantId;
var tokenCredentialOptions = new TokenCredentialOptions
{
AuthorityHost = new Uri(GetAuthorityUrl(authContext))
};
if (IsAuthFlowNotSupported())
{
throw new Exception(string.Format(CultureInfo.InvariantCulture, ErrorConstants.Message.AuthNotSupported, "Username and password"));
}
var environmentCredential = new EnvironmentCredential(tokenCredentialOptions);
return await Task.FromResult(environmentCredential).ConfigureAwait(false);
}
private static bool IsAuthFlowNotSupported()
{
return ((!string.IsNullOrEmpty(EnvironmentVariables.Username) && !string.IsNullOrEmpty(EnvironmentVariables.Password))
&& (string.IsNullOrEmpty(EnvironmentVariables.ClientSecret) && string.IsNullOrEmpty(EnvironmentVariables.ClientCertificatePath)));
}
private static bool IsWamSupported()
{
return GraphSession.Instance.GraphOption.EnableWAMForMSGraph && SharedUtilities.IsWindowsPlatform();
}
private static async Task<TokenCredential> GetClientSecretCredentialAsync(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var clientSecretCredentialOptions = new ClientSecretCredentialOptions
{
AuthorityHost = new Uri(GetAuthorityUrl(authContext)),
TokenCachePersistenceOptions = GetTokenCachePersistenceOptions(authContext)
};
var clientSecretCredential = new ClientSecretCredential(authContext.TenantId, authContext.ClientId, authContext.ClientSecret.ConvertToString(), clientSecretCredentialOptions);
return await Task.FromResult(clientSecretCredential).ConfigureAwait(false);
}
private static async Task<TokenCredential> GetManagedIdentityCredentialAsync(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var userAccountId = authContext.ManagedIdentityId.StartsWith(Constants.DefaultMsiIdPrefix) ? null : authContext.ManagedIdentityId;
return await Task.FromResult(new ManagedIdentityCredential(userAccountId)).ConfigureAwait(false);
}
private static async Task<InteractiveBrowserCredential> GetInteractiveBrowserCredentialAsync(IAuthContext authContext, CancellationToken cancellationToken = default)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var interactiveOptions = IsWamSupported() ?
new InteractiveBrowserCredentialBrokerOptions(WindowHandleUtlities.GetConsoleOrTerminalWindow()) :
new InteractiveBrowserCredentialOptions();
interactiveOptions.ClientId = authContext.ClientId;
interactiveOptions.TenantId = authContext.TenantId ?? "common";
interactiveOptions.AuthorityHost = new Uri(GetAuthorityUrl(authContext));
interactiveOptions.TokenCachePersistenceOptions = GetTokenCachePersistenceOptions(authContext);
var interactiveBrowserCredential = new InteractiveBrowserCredential(interactiveOptions);
var popTokenRequestContext = new PopTokenRequestContext();
if (GraphSession.Instance.GraphOption.EnableATPoPForMSGraph)
{
popTokenRequestContext = await CreatePopTokenRequestContext(authContext);
GraphSession.Instance.GraphRequestPopContext.PopInteractiveBrowserCredential = interactiveBrowserCredential;
}
if (!File.Exists(Constants.AuthRecordPath))
{
AuthenticationRecord authRecord;
if (IsWamSupported())
{
// Adding a scenario to account for Access Token Proof of Possession
if (GraphSession.Instance.GraphOption.EnableATPoPForMSGraph)
{
authRecord = await Task.Run(() =>
{
// Run the thread in MTA.
return interactiveBrowserCredential.AuthenticateAsync(popTokenRequestContext, cancellationToken);
});
}
else
{
authRecord = await Task.Run(() =>
{
// Run the thread in MTA.
return interactiveBrowserCredential.Authenticate(new TokenRequestContext(authContext.Scopes), cancellationToken);
});
}
}
else
{
authRecord = await Task.Run(() =>
{
// Run the thread in MTA.
return interactiveBrowserCredential.AuthenticateAsync(new TokenRequestContext(authContext.Scopes), cancellationToken);
});
}
await WriteAuthRecordAsync(authRecord).ConfigureAwait(false);
return interactiveBrowserCredential;
}
interactiveOptions.AuthenticationRecord = await ReadAuthRecordAsync().ConfigureAwait(false);
return new InteractiveBrowserCredential(interactiveOptions);
}
private static async Task<DeviceCodeCredential> GetDeviceCodeCredentialAsync(IAuthContext authContext, CancellationToken cancellationToken = default)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var deviceCodeOptions = new DeviceCodeCredentialOptions
{
ClientId = authContext.ClientId,
TenantId = authContext.TenantId,
AuthorityHost = new Uri(GetAuthorityUrl(authContext)),
TokenCachePersistenceOptions = GetTokenCachePersistenceOptions(authContext),
DeviceCodeCallback = (code, cancellation) =>
{
GraphSession.Instance.OutputWriter.WriteObject(code.Message);
return Task.CompletedTask;
}
};
if (!File.Exists(Constants.AuthRecordPath))
{
var deviceCodeCredential = new DeviceCodeCredential(deviceCodeOptions);
var authRecord = await deviceCodeCredential.AuthenticateAsync(new TokenRequestContext(authContext.Scopes), cancellationToken).ConfigureAwait(false);
await WriteAuthRecordAsync(authRecord).ConfigureAwait(false);
return deviceCodeCredential;
}
deviceCodeOptions.AuthenticationRecord = await ReadAuthRecordAsync().ConfigureAwait(false);
return new DeviceCodeCredential(deviceCodeOptions);
}
private static async Task<ClientCertificateCredential> GetClientCertificateCredentialAsync(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var clientCredentialOptions = new ClientCertificateCredentialOptions
{
AuthorityHost = new Uri(GetAuthorityUrl(authContext)),
TokenCachePersistenceOptions = GetTokenCachePersistenceOptions(authContext),
SendCertificateChain = authContext.SendCertificateChain
};
var clientCertificateCredential = new ClientCertificateCredential(authContext.TenantId, authContext.ClientId, GetCertificate(authContext), clientCredentialOptions);
return await Task.FromResult(clientCertificateCredential).ConfigureAwait(false);
}
private static TokenCachePersistenceOptions GetTokenCachePersistenceOptions(IAuthContext authContext)
{
return authContext.ContextScope == ContextScope.Process
? GraphSession.Instance.InMemoryTokenCache.GetTokenCachePersistenceOptions()
: new TokenCachePersistenceOptions { Name = Constants.CacheName };
}
/// <summary>
/// Gets a <see cref="AzureIdentityAccessTokenProvider"/> using the provided <see cref="IAuthContext"/>
/// </summary>
/// <param name="authContext">The <see cref="IAuthContext"/> to get a token credential for.</param>
/// <returns>A <see cref="AzureIdentityAccessTokenProvider"/> based on provided <see cref="IAuthContext"/>.</returns>
public static async Task<AzureIdentityAccessTokenProvider> GetAuthenticationProviderAsync(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var tokenCredential = await GetTokenCredentialAsync(authContext, default).ConfigureAwait(false);
return new AzureIdentityAccessTokenProvider(credential:tokenCredential, observabilityOptions: null,isCaeEnabled: true,scopes: GetScopes(authContext));
}
public static async Task<IAuthContext> AuthenticateAsync(IAuthContext authContext, CancellationToken cancellationToken)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
IAuthContext signInAuthContext = null;
bool retrySignIn = true;
int retryCount = 0;
while (retrySignIn && retryCount <= Constants.MaxAuthRetry)
{
try
{
// Write MSAL logs to debug stream.
using (AzureEventSourceListener listener = new AzureEventSourceListener(
(args, message) => GraphSession.Instance.OutputWriter.WriteDebug($"{message}"),
level: EventLevel.Informational))
{
signInAuthContext = await SignInAsync(authContext, cancellationToken).ConfigureAwait(false);
retrySignIn = false;
};
}
catch (AuthenticationFailedException authEx)
{
if (authEx.InnerException is MsalCachePersistenceException)
{
// Can't securely persist token on disk. Retry with in-memory cache.
authContext.ContextScope = ContextScope.Process;
retrySignIn = true;
retryCount++;
}
else if (authEx.InnerException is MsalClientException msalClientEx
&& string.Equals(msalClientEx?.ErrorCode, MsalError.LinuxXdgOpen, StringComparison.InvariantCultureIgnoreCase) ||
(authEx.Message?.ToLower(CultureInfo.InvariantCulture)?.Contains("unable to open a web page") ?? false))
{
// Can't open browser. Retry with device code authentication.
authContext.TokenCredentialType = TokenCredentialType.DeviceCode;
retrySignIn = true;
retryCount++;
}
else if (authEx.InnerException is MsalServiceException msalServiceEx
&& msalServiceEx.StatusCode == 400 && string.Equals(msalServiceEx.ErrorCode, "invalid_scope", StringComparison.InvariantCultureIgnoreCase)
&& string.IsNullOrWhiteSpace(authContext.TenantId)
&& authContext.TokenCredentialType == TokenCredentialType.DeviceCode)
{
// MSAL scope validation error. Ask customer to specify sign-in audience or tenant Id.
throw new MsalClientException(msalServiceEx.ErrorCode, $"{msalServiceEx.Message}.\r\n{ErrorConstants.Message.InvalidScope}", msalServiceEx);
}
else
throw;
}
catch (TaskCanceledException taskCanceledEx)
{
throw new Exception(string.Format(CultureInfo.CurrentCulture, ErrorConstants.Message.AuthenticationTimeout, Constants.MaxAuthenticationTimeOutInSeconds), taskCanceledEx);
}
catch (Exception)
{
throw;
}
}
return signInAuthContext;
}
private static async Task<IAuthContext> SignInAsync(IAuthContext authContext, CancellationToken cancellationToken = default)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
var tokenCredential = await GetTokenCredentialAsync(authContext, cancellationToken).ConfigureAwait(false);
var token = await tokenCredential.GetTokenAsync(new TokenRequestContext(GetScopes(authContext)), cancellationToken).ConfigureAwait(false);
JwtHelpers.DecodeJWT(token.Token, account: null, ref authContext);
return authContext;
}
private static string[] GetScopes(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
switch (authContext.AuthType)
{
case AuthenticationType.AppOnly:
case AuthenticationType.EnvironmentVariable:
return new[] { $"{GraphSession.Instance.Environment?.GraphEndpoint ?? Constants.DefaultGraphEndpoint}/.default" };
case AuthenticationType.ManagedIdentity:
return new[] { GraphSession.Instance.Environment.GraphEndpoint };
default:
return authContext.Scopes;
}
}
/// <summary>
/// Gets an authority URL from the provided <see cref="IAuthContext"/>.
/// </summary>
/// <param name="authContext">The <see cref="IAuthContext"/> to get an authority URL for.</param>
/// <returns></returns>
private static string GetAuthorityUrl(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
string audience = authContext.TenantId ?? Constants.DefaultTenant;
return GraphSession.Instance.Environment != null
? $"{GraphSession.Instance.Environment.AzureADEndpoint}/{audience}"
: $"{Constants.DefaultAzureADEndpoint}/{audience}";
}
/// <summary>
/// Gets a certificate based on the current context.
/// Priority is Name, ThumbPrint, then In-Memory Cert
/// </summary>
/// <param name="authContext">Current <see cref="IAuthContext"/> context</param>
/// <returns>A <see cref="X509Certificate2"/> based on provided <see cref="IAuthContext"/> context</returns>
/// <returns>A <see cref="X509Certificate2"/> based on provided <see cref="IAuthContext"/> context</returns>
private static X509Certificate2 GetCertificate(IAuthContext authContext)
{
if (authContext is null)
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
if (!string.IsNullOrWhiteSpace(authContext.CertificateSubjectName))
{
if (TryFindCertificateBySubjectName(authContext.CertificateSubjectName, StoreLocation.CurrentUser, out X509Certificate2 certificate) ||
TryFindCertificateBySubjectName(authContext.CertificateSubjectName, StoreLocation.LocalMachine, out certificate))
return certificate;
else
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorConstants.Message.CertificateNotFound,
"subject name",
authContext.CertificateSubjectName));
}
else if (!string.IsNullOrWhiteSpace(authContext.CertificateThumbprint))
{
if (TryFindCertificateByThumbprint(authContext.CertificateThumbprint, StoreLocation.CurrentUser, out X509Certificate2 certificate) ||
TryFindCertificateByThumbprint(authContext.CertificateThumbprint, StoreLocation.LocalMachine, out certificate))
return certificate;
else
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, ErrorConstants.Message.CertificateNotFound,
"thumbprint",
authContext.CertificateThumbprint));
}
else
return authContext.Certificate;
}
/// <summary>
/// Gets unexpired certificate using the specified certificate store using the provided thumbprint.
/// </summary>
/// <param name="thumbprint">Thumbprint of the certificate to fetch.</param>
/// <param name="location">The certificate store location.</param>
/// <param name="certificate">Unexpired certificate.</param>
private static bool TryFindCertificateByThumbprint(string thumbprint, StoreLocation location, out X509Certificate2 certificate)
{
using (X509Store xStore = new X509Store(StoreName.My, location))
{
xStore.Open(OpenFlags.ReadOnly);
// Get unexpired certificates with the specified name.
X509Certificate2Collection unexpiredCerts = xStore.Certificates
.Find(X509FindType.FindByTimeValid, DateTime.Now, validOnly: false)
.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
xStore.Close();
// Only return current cert.
certificate = unexpiredCerts
.OfType<X509Certificate2>()
.OrderByDescending(c => c.NotBefore)
.FirstOrDefault();
return certificate != null;
}
}
/// <summary>
/// Gets unexpired certificate using the specified certificate store using the provided subject distinguished name.
/// </summary>
/// <param name="subjectName">Subject distinguished name of the certificate to fetch.</param>
/// <param name="location">The certificate store location.</param>
/// <param name="certificate">Unexpired certificate.</param>
private static bool TryFindCertificateBySubjectName(string subjectName, StoreLocation location, out X509Certificate2 certificate)
{
using (X509Store xStore = new X509Store(StoreName.My, location))
{
xStore.Open(OpenFlags.ReadOnly);
// Get unexpired certificates with the specified name.
X509Certificate2Collection unexpiredCerts = xStore.Certificates
.Find(X509FindType.FindByTimeValid, DateTime.Now, validOnly: false)
.Find(X509FindType.FindBySubjectDistinguishedName, subjectName, validOnly: false);
xStore.Close();
// Only return current cert.
certificate = unexpiredCerts
.OfType<X509Certificate2>()
.OrderByDescending(c => c.NotBefore)
.FirstOrDefault();
return certificate != null;
}
}
/// <summary>
/// Signs out of the current session using the provided <see cref="IAuthContext"/>.
/// </summary>
/// <param name="authContext">The <see cref="IAuthContext"/> to sign-out from.</param>
public static async Task<IAuthContext> LogoutAsync()
{
var authContext = GraphSession.Instance.AuthContext;
GraphSession.Instance.InMemoryTokenCache?.ClearCache();
GraphSession.Instance.AuthContext = null;
GraphSession.Instance.GraphHttpClient = null;
await DeleteAuthRecordAsync().ConfigureAwait(false);
return authContext;
}
private static async Task<AuthenticationRecord> ReadAuthRecordAsync()
{
// Try to create directory if it doesn't exist.
Directory.CreateDirectory(Constants.GraphDirectoryPath);
if (!File.Exists(Constants.AuthRecordPath))
return null;
using (FileStream authRecordStream = new FileStream(Constants.AuthRecordPath, FileMode.Open, FileAccess.Read))
return await AuthenticationRecord.DeserializeAsync(authRecordStream).ConfigureAwait(false);
}
public static async Task WriteAuthRecordAsync(AuthenticationRecord authRecord)
{
// Try to create directory if it doesn't exist.
Directory.CreateDirectory(Constants.GraphDirectoryPath);
using (FileStream authRecordStream = new FileStream(Constants.AuthRecordPath, FileMode.Create, FileAccess.Write))
await authRecord.SerializeAsync(authRecordStream).ConfigureAwait(false);
}
public static Task DeleteAuthRecordAsync()
{
if (File.Exists(Constants.AuthRecordPath))
File.Delete(Constants.AuthRecordPath);
return Task.CompletedTask;
}
private static async Task<PopTokenRequestContext> CreatePopTokenRequestContext(IAuthContext authContext)
{
// Creating a httpclient that would handle all pop calls
Uri popResourceUri = GraphSession.Instance.GraphRequestPopContext.Uri ?? new Uri("https://graph.microsoft.com/beta/organization");
HttpClient popHttpClient = new(new HttpClientHandler());
// Find the nonce in the WWW-Authenticate header in the response.
var popMethod = GraphSession.Instance.GraphRequestPopContext.HttpMethod ?? HttpMethod.Get;
var popResponse = await popHttpClient.SendAsync(new HttpRequestMessage(popMethod, popResourceUri));
// Refresh token logic --- start
var popPipelineOptions = new HttpPipelineOptions(new PopClientOptions()
{
});
GraphSession.Instance.GraphRequestPopContext.PopPipeline = HttpPipelineBuilder.Build(popPipelineOptions, new HttpPipelineTransportOptions());
var popRequest = GraphSession.Instance.GraphRequestPopContext.PopPipeline.CreateRequest();
popRequest.Method = RequestMethod.Parse(popMethod.Method.ToUpper());
popRequest.Uri.Reset(popResourceUri);
// Refresh token logic --- end
var popContext = new PopTokenRequestContext(authContext.Scopes, isProofOfPossessionEnabled: true, proofOfPossessionNonce: WwwAuthenticateParameters.CreateFromAuthenticationHeaders(popResponse.Headers, "Pop").Nonce, request: popRequest);
return popContext;
}
}
internal class PopClientOptions : ClientOptions
{
}
}