-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathAuthenticationManager.cs
More file actions
2109 lines (1903 loc) · 117 KB
/
Copy pathAuthenticationManager.cs
File metadata and controls
2109 lines (1903 loc) · 117 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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.AppConfig;
using Microsoft.Identity.Client.Broker;
using Microsoft.Identity.Client.Extensibility;
using Microsoft.Identity.Client.Extensions.Msal;
using Microsoft.SharePoint.Client;
using PnP.Core.Services;
using PnP.Framework.Utilities;
using PnP.Framework.Utilities.Context;
using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace PnP.Framework
{
/// <summary>
/// Enum to identify the supported Office 365 hosting environments
/// </summary>
public enum AzureEnvironment
{
/// <summary>
///
/// </summary>
Production = 0,
/// <summary>
///
/// </summary>
PPE = 1,
/// <summary>
///
/// </summary>
China = 2,
/// <summary>
///
/// </summary>
Germany = 3,
/// <summary>
///
/// </summary>
USGovernment = 4,
/// <summary>
///
/// </summary>
USGovernmentHigh = 5,
/// <summary>
///
/// </summary>
USGovernmentDoD = 6,
/// <summary>
///
/// </summary>
DelosCloud = 7,
/// <summary>
///
/// </summary>
BleuCloud = 8,
/// <summary>
///
/// </summary>
GovSGCloud = 9,
/// <summary>
/// Custom cloud configuration, specify the endpoints manually
/// </summary>
Custom = 100
}
/// <summary>
/// A Known Client Ids to use for authentication
/// </summary>
public enum KnownClientId
{
/// <summary>
/// SPO Management Shell app
/// </summary>
SPOManagementShell
}
/// <summary>
/// This manager class can be used to obtain a SharePoint Client Context object
/// </summary>
public class AuthenticationManager : IDisposable
{
/// <summary>
/// The client id of the Microsoft SharePoint Online Management Shell application
/// </summary>
public const string CLIENTID_SPOMANAGEMENTSHELL = "9bc3ab49-b65d-410a-85ad-de819febfddc";
private readonly IPublicClientApplication publicClientApplication;
private readonly IConfidentialClientApplication confidentialClientApplication;
private readonly IManagedIdentityApplication mi;
// Azure environment setup
private AzureEnvironment azureEnvironment;
// When azureEnvironment = Custom then use these strings to keep track of the respective URLs to use
private string microsoftGraphEndPoint;
private string azureADLoginEndPoint;
private readonly ClientContextType authenticationType;
private readonly string username;
private readonly SecureString password;
private readonly UserAssertion assertion;
private readonly Func<DeviceCodeResult, Task> deviceCodeCallback;
private readonly ICustomWebUi customWebUi;
private readonly ACSTokenGenerator acsTokenGenerator;
private IMsalHttpClientFactory httpClientFactory;
private readonly SecureString accessToken;
private readonly IAuthenticationProvider authenticationProvider;
private readonly PnPContext pnpContext;
/// <summary>
/// The endpoint at which the Managed Identity Service is being hosted from which a token can be acquired
/// </summary>
private readonly string managedIdendityEndpoint;
/// <summary>
/// Identity header available as an environment variable in Azure. Used to help mitigate server-side request forgery (SSRF) attacks.
/// </summary>
private readonly string managedIdentityHeader;
/// <summary>
/// Identifier of the User Assigned Managed Identity in Azure. Used in combination with
/// </summary>
private readonly string managedIdentityUserAssignedIdentifier;
/// <summary>
/// The type of Managed Identity used
/// </summary>
private readonly ManagedIdentityType? managedIdentityType;
public CookieContainer CookieContainer { get; set; }
private IMsalHttpClientFactory HttpClientFactory
{
get
{
if (httpClientFactory == null)
{
httpClientFactory = new Http.MsalHttpClientFactory();
}
return httpClientFactory;
}
}
#region Creation
public static AuthenticationManager CreateWithAccessToken(SecureString accessToken)
{
return new AuthenticationManager(accessToken);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts through device code authentication
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="deviceCodeCallback">The callback that will be called with device code information.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithDeviceLogin(string clientId, Func<DeviceCodeResult, Task> deviceCodeCallback, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, null, deviceCodeCallback, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts through device code authentication
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="deviceCodeCallback">The callback that will be called with device code information.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithDeviceLogin(string clientId, string tenantId, Func<DeviceCodeResult, Task> deviceCodeCallback, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, tenantId, deviceCodeCallback, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire access tokens and client contexts using the Azure AD Interactive flow.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="openBrowserCallback">This callback will be called providing the URL and port to open during the authentication flow</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="successMessageHtml">Allows you to override the success message. Notice that a success header message will be added.</param>
/// <param name="failureMessageHtml">llows you to override the failure message. Notice that a failed header message will be added and the error message will be appended.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called to register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
/// <param name="useWAM">If true, uses WAM for authentication. Works only on Windows OS. Default is false</param>
public static AuthenticationManager CreateWithInteractiveLogin(string clientId, Action<string, int> openBrowserCallback, string tenantId = null, string successMessageHtml = null, string failureMessageHtml = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null, bool useWAM = false)
{
return new AuthenticationManager(clientId, Utilities.OAuth.DefaultBrowserUi.FindFreeLocalhostRedirectUri(), tenantId, azureEnvironment, tokenCacheCallback, new Utilities.OAuth.DefaultBrowserUi(openBrowserCallback, successMessageHtml, failureMessageHtml), useWAM);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire access tokens and client contexts using the Azure AD Interactive flow.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="openBrowserCallback">This callback will be called providing the URL and port to open during the authentication flow</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="successFullMessageHtml">Allows you to override the success message. You will have to provide the full HTML document.</param>
/// <param name="failureFullMessageHtml">llows you to override the failure message. You will have to provide the full HTML document.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called to register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
/// <param name="useWAM">If true, uses WAM for authentication. Works only on Windows OS. Default is false</param>
public static AuthenticationManager CreateWithInteractiveWebBrowserLogin(string clientId, Action<string, int> openBrowserCallback, string tenantId = null, string successFullMessageHtml = null, string failureFullMessageHtml = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null, bool useWAM = false)
{
return new AuthenticationManager(clientId, Utilities.OAuth.DefaultBrowserUi.FindFreeLocalhostRedirectUri(), tenantId, azureEnvironment, tokenCacheCallback, new Utilities.OAuth.DefaultBrowserUi(openBrowserCallback, successFullMessageHtml, failureFullMessageHtml, true), useWAM);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire access tokens and client contexts using the Azure AD Interactive flow.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
/// <param name="customWebUi">Optional ICustomWebUi object to fully customize the feedback behavior</param>
/// <param name="useWAM">If true, uses WAM for authentication. Works only on Windows OS</param>
public static AuthenticationManager CreateWithInteractiveLogin(string clientId, string redirectUrl = null, string tenantId = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null, ICustomWebUi customWebUi = null, bool useWAM = false)
{
return new AuthenticationManager(clientId, redirectUrl ?? Utilities.OAuth.DefaultBrowserUi.FindFreeLocalhostRedirectUri(), tenantId, azureEnvironment, tokenCacheCallback, customWebUi, useWAM);
}
/// <summary>
/// Creates a new instance of the Authentication Manager that works with a System Assigned or User Assigned Managed Identity in Azure
/// </summary>
/// <param name="endpoint">The endpoint at which the Managed Identity Service is being hosted from which a token can be acquired</param>
/// <param name="identityHeader">Identity header available as an environment variable in Azure. Used to help mitigate server-side request forgery (SSRF) attacks.</param>
/// <param name="managedIdentityType">Type of Managed Identity that should be used. Defaults to System Assigned Managed Identity.</param>
/// <param name="managedIdentityUserAssignedIdentifier">The identifier of the User Assigned Managed Identity. Can be the clientId, objectId or resourceId. Mandatory when <paramref name="managedIdentityType"/> is not SystemAssigned. Should be omitted if it is SystemAssigned.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
public static AuthenticationManager CreateWithManagedIdentity(string endpoint, string identityHeader, ManagedIdentityType managedIdentityType = ManagedIdentityType.SystemAssigned, string managedIdentityUserAssignedIdentifier = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
{
return new AuthenticationManager(endpoint, identityHeader, managedIdentityType, managedIdentityUserAssignedIdentifier, azureEnvironment);
}
/// <summary>
/// Creates a new instance of the Authentication Manager that works with a User Assigned Managed Identity (MI) in Azure configured as a Federated Identity Credential on an Entra ID application registration.
/// </summary>
/// <param name="endpoint">The endpoint at which the Managed Identity Service is being hosted from which a token can be acquired</param>
/// <param name="identityHeader">Identity header available as an environment variable in Azure. Used to help mitigate server-side request forgery (SSRF) attacks.</param>
/// <param name="appClientId">Client ID of the Entra ID application registration where the MI is added as a Federated Identity Credential. If you intend to access Graph/SPO in another tenant, this must be a multi-tenant application. A service principal for the same app should be created/consented to in target tenant.</param>
/// <param name="appTenantId">Tenant ID of the Entra ID application registration where the MI is added as a Federated Identity Credential. This must be registered in same tenant as the MI.</param>
/// <param name="managedIdentityType">Type of Managed Identity that should be used. Cannot be System Assigned.</param>
/// <param name="managedIdentityUserAssignedIdentifier">The identifier of the User Assigned Managed Identity. Can be the clientId, objectId or resourceId.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
public static AuthenticationManager CreateWithManagedIdentityFederatedIdentityCredential(string endpoint, string identityHeader, string appClientId, string appTenantId, ManagedIdentityType managedIdentityType, string managedIdentityUserAssignedIdentifier, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
{
return new AuthenticationManager(endpoint, identityHeader, appClientId, appTenantId, managedIdentityType, managedIdentityUserAssignedIdentifier, azureEnvironment);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="username">The username to use for authentication</param>
/// <param name="password">The password to use for authentication</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithCredentials(string clientId, string username, SecureString password, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, username, password, redirectUrl, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="certificate">A valid certificate</param>
/// <param name="tenantId">Tenant id or tenant url</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithCertificate(string clientId, X509Certificate2 certificate, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, certificate, tenantId, redirectUrl, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="certificatePath">A valid path to a certificate file</param>
/// <param name="certificatePassword">The password for the certificate</param>
/// <param name="tenantId">The tenant id (guid) or name (e.g. contoso.onmicrosoft.com) </param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithCertificate(string clientId, string certificatePath, string certificatePassword, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, certificatePath, certificatePassword, tenantId, redirectUrl, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="storeName">The name of the certificate store to find the certificate in.</param>
/// <param name="storeLocation">The location of the certificate store to find the certificate in.</param>
/// <param name="thumbPrint">The thumbprint of the certificate to use.</param>
/// <param name="tenantId">The tenant id (guid) or name (e.g. contoso.onmicrosoft.com) </param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithCertificate(string clientId, StoreName storeName, StoreLocation storeLocation, string thumbPrint, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, storeName, storeLocation, thumbPrint, tenantId, redirectUrl, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContext.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication.</param>
/// <param name="clientSecret">The client secret of the Azure AD application to use for authentication.</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="userAssertion">The user assertion (token) of the user on whose behalf to acquire the context</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public static AuthenticationManager CreateWithOnBehalfOf(string clientId, string clientSecret, UserAssertion userAssertion, string tenantId = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null)
{
return new AuthenticationManager(clientId, clientSecret, userAssertion, tenantId, azureEnvironment, tokenCacheCallback);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire an authenticated ClientContext.
/// </summary>
/// <param name="authenticationProvider">PnP Core SDK authentication provider that will deliver the access token</param>
/// <returns></returns>
public static AuthenticationManager CreateWithPnPCoreSdk(IAuthenticationProvider authenticationProvider)
{
return new AuthenticationManager(authenticationProvider);
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire an authenticated ClientContext.
/// </summary>
/// <param name="pnpContext">PnP Core SDK authentication provider that will deliver the access token</param>
/// <returns></returns>
public static AuthenticationManager CreateWithPnPCoreSdk(PnPContext pnpContext)
{
return new AuthenticationManager(pnpContext);
}
#endregion
#region Construction
/// <summary>
/// Empty constructor, to be used if you want to execute ACS based authentication methods.
/// </summary>
public AuthenticationManager()
{
#if !NET9_0
// Set the TLS preference. Needed on some server os's to work when Office 365 removes support for TLS 1.0
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
#endif
}
private AuthenticationManager(ACSTokenGenerator oAuthAuthenticationProvider) : this()
{
this.acsTokenGenerator = oAuthAuthenticationProvider;
authenticationType = ClientContextType.SharePointACSAppOnly;
}
public AuthenticationManager(SecureString accessToken)
{
this.accessToken = accessToken;
authenticationType = ClientContextType.AccessToken;
}
/// <summary>
/// Creates a new instance of the Authentication Manager that works with a System Assigned or User Assigned Managed Identity in Azure
/// </summary>
/// <param name="endpoint">The endpoint at which the Managed Identity Service is being hosted from which a token can be acquired</param>
/// <param name="identityHeader">Identity header available as an environment variable in Azure. Used to help mitigate server-side request forgery (SSRF) attacks.</param>
/// <param name="managedIdentityType">Type of Managed Identity that should be used. Defaults to System Assigned Managed Identity.</param>
/// <param name="managedIdentityUserAssignedIdentifier">The identifier of the User Assigned Managed Identity. Can be the clientId, objectId or resourceId. Mandatory when <paramref name="managedIdentityType"/> is not SystemAssigned. Should be omitted if it is SystemAssigned.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
public AuthenticationManager(string endpoint, string identityHeader, ManagedIdentityType managedIdentityType = ManagedIdentityType.SystemAssigned, string managedIdentityUserAssignedIdentifier = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
{
if (managedIdentityType != ManagedIdentityType.SystemAssigned && string.IsNullOrWhiteSpace(managedIdentityUserAssignedIdentifier))
{
throw new ArgumentException($"When {nameof(managedIdentityType)} is not SystemAssigned, {nameof(managedIdentityUserAssignedIdentifier)} must be provided", nameof(managedIdentityType));
}
authenticationType = managedIdentityType == ManagedIdentityType.SystemAssigned ? ClientContextType.SystemAssignedManagedIdentity : ClientContextType.UserAssignedManagedIdentity;
this.managedIdentityType = managedIdentityType;
this.managedIdentityUserAssignedIdentifier = managedIdentityUserAssignedIdentifier;
this.azureEnvironment = azureEnvironment;
// Construct the URL to call to get the token based on the type of Managed Identity in use
switch (managedIdentityType)
{
case ManagedIdentityType.UserAssignedByClientId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with client ID: {managedIdentityUserAssignedIdentifier}");
mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedClientId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
case ManagedIdentityType.UserAssignedByObjectId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with object/principal ID: {managedIdentityUserAssignedIdentifier}");
mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedObjectId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
case ManagedIdentityType.UserAssignedByResourceId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with Azure Resource ID: {managedIdentityUserAssignedIdentifier}");
mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedResourceId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
case ManagedIdentityType.SystemAssigned:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, "Using the system assigned managed identity");
mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.SystemAssigned).WithHttpClientFactory(HttpClientFactory).Build();
break;
}
}
/// <summary>
/// Creates a new instance of the Authentication Manager that works with a User Assigned Managed Identity (MI) in Azure configured as a Federated Identity Credential on an Entra ID application registration.
/// </summary>
/// <param name="endpoint">The endpoint at which the Managed Identity Service is being hosted from which a token can be acquired</param>
/// <param name="identityHeader">Identity header available as an environment variable in Azure. Used to help mitigate server-side request forgery (SSRF) attacks.</param>
/// <param name="appClientId">Client ID of the Entra ID application registration where the MI is added as a Federated Identity Credential. If you intend to access Graph/SPO in another tenant, this must be a multi-tenant application. A service principal for the same app should be created/consented to in target tenant.</param>
/// <param name="appTenantId">Tenant ID of the Entra ID application registration where the MI is added as a Federated Identity Credential. This must be registered in same tenant as the MI.</param>
/// <param name="managedIdentityType">Type of Managed Identity that should be used. Cannot be System Assigned.</param>
/// <param name="managedIdentityUserAssignedIdentifier">The identifier of the User Assigned Managed Identity. Can be the clientId, objectId or resourceId.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
public AuthenticationManager(string endpoint, string identityHeader, string appClientId, string appTenantId, ManagedIdentityType managedIdentityType, string managedIdentityUserAssignedIdentifier, AzureEnvironment azureEnvironment = AzureEnvironment.Production)
{
if (managedIdentityType == ManagedIdentityType.SystemAssigned)
{
throw new ArgumentException($"SystemAssigned managed identity is not currently supported for federated identity credentials flow.");
}
if (string.IsNullOrWhiteSpace(managedIdentityUserAssignedIdentifier))
{
throw new ArgumentException($"When {nameof(managedIdentityType)} is not SystemAssigned, {nameof(managedIdentityUserAssignedIdentifier)} must be provided", nameof(managedIdentityType));
}
if (string.IsNullOrWhiteSpace(appClientId))
{
throw new ArgumentException($"{nameof(appClientId)} must be provided.");
}
if (string.IsNullOrWhiteSpace(appTenantId))
{
throw new ArgumentException($"{nameof(appTenantId)} must be provided.");
}
authenticationType = ClientContextType.UserAssignedManagedIdentityFederatedCredential;
this.managedIdentityType = managedIdentityType;
this.managedIdentityUserAssignedIdentifier = managedIdentityUserAssignedIdentifier;
this.azureEnvironment = azureEnvironment;
// Construct the URL to call to get the token based on the type of Managed Identity in use
IManagedIdentityApplication managedIdentityApplication = null;
switch (managedIdentityType)
{
case ManagedIdentityType.UserAssignedByClientId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with client ID: {managedIdentityUserAssignedIdentifier} as Federated Credential for client ID: {appClientId} in tenant: {appTenantId}");
managedIdentityApplication = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedClientId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
case ManagedIdentityType.UserAssignedByObjectId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with object/principal ID: {managedIdentityUserAssignedIdentifier} as Federated Credential for client ID: {appClientId} in tenant: {appTenantId}");
managedIdentityApplication = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedObjectId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
case ManagedIdentityType.UserAssignedByResourceId:
Diagnostics.Log.Debug(Constants.LOGGING_SOURCE, $"Using the user assigned managed identity with Azure Resource ID: {managedIdentityUserAssignedIdentifier} as Federated Credential for client ID: {appClientId} in tenant: {appTenantId}");
managedIdentityApplication = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedResourceId(managedIdentityUserAssignedIdentifier)).WithHttpClientFactory(HttpClientFactory).Build();
break;
}
// Create ConfidentialClientApplication with the managed identity application used as an assertion provider with token exchange audience
var audience = "api://AzureADTokenExchange";
async Task<string> miAssertionProvider(AssertionRequestOptions _)
{
var miResult = await managedIdentityApplication.AcquireTokenForManagedIdentity(audience)
.ExecuteAsync()
.ConfigureAwait(false);
return miResult.AccessToken;
}
confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(appClientId)
.WithTenantId(appTenantId)
.WithClientAssertion(miAssertionProvider)
.WithLegacyCacheCompatibility(false)
.Build();
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="username">The username to use for authentication</param>
/// <param name="password">The password to use for authentication</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, string username, SecureString password, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
var builder = PublicClientApplicationBuilder.Create(clientId).WithAuthority($"{azureADEndPoint}/organizations/").WithHttpClientFactory(HttpClientFactory);
if (!string.IsNullOrEmpty(redirectUrl))
{
builder = builder.WithRedirectUri(redirectUrl);
}
builder.WithLegacyCacheCompatibility(false);
this.username = username;
this.password = password;
publicClientApplication = builder.Build();
// register tokencache if callback provided
tokenCacheCallback?.Invoke(publicClientApplication.UserTokenCache);
authenticationType = ClientContextType.AzureADCredentials;
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire access tokens and client contexts using the Azure AD Interactive flow.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="openBrowserCallback">This callback will be called providing the URL and port to open during the authentication flow</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="successMessageHtml">Allows you to override the success message. Notice that a success header message will be added.</param>
/// <param name="failureMessageHtml">llows you to override the failure message. Notice that a failed header message will be added and the error message will be appended.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called to register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
/// <param name="useWAM">If true, uses WAM for authentication. Works only on Windows OS</param>
public AuthenticationManager(string clientId, Action<string, int> openBrowserCallback, string tenantId = null, string successMessageHtml = null, string failureMessageHtml = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null, bool useWAM = false) : this(clientId, Utilities.OAuth.DefaultBrowserUi.FindFreeLocalhostRedirectUri(), tenantId, azureEnvironment, tokenCacheCallback, new Utilities.OAuth.DefaultBrowserUi(openBrowserCallback, successMessageHtml, failureMessageHtml), useWAM = false)
{
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire access tokens and client contexts using the Azure AD Interactive flow.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
/// <param name="customWebUi">Optional ICustomWebUi object to fully customize the feedback behavior</param>
/// <param name="useWAM">If true, uses WAM for authentication. Works only for Windows OS platform</param>
public AuthenticationManager(string clientId, string redirectUrl = null, string tenantId = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null, ICustomWebUi customWebUi = null, bool useWAM = false) : this()
{
this.azureEnvironment = azureEnvironment;
PublicClientApplicationBuilder builder = PublicClientApplicationBuilder.Create(clientId).WithHttpClientFactory(HttpClientFactory);
builder = GetBuilderWithAuthority(builder, azureEnvironment, tenantId);
if (!string.IsNullOrEmpty(tenantId))
{
builder = builder.WithTenantId(tenantId);
}
if (useWAM && (SharedUtilities.IsWindowsPlatform() || SharedUtilities.IsLinuxPlatform()))
{
if (SharedUtilities.IsWindowsPlatform())
{
BrokerOptions brokerOptions = new(BrokerOptions.OperatingSystems.Windows)
{
Title = "Login with M365 PnP",
ListOperatingSystemAccounts = true,
};
builder = builder.WithBroker(brokerOptions).WithDefaultRedirectUri().WithParentActivityOrWindow(OSHandleUtilities.GetConsoleOrTerminalWindow);
}
else if (SharedUtilities.IsLinuxPlatform())
{
BrokerOptions brokerOptions = new(BrokerOptions.OperatingSystems.Linux)
{
Title = "Login with M365 PnP",
ListOperatingSystemAccounts = true,
};
builder = builder.WithBroker(brokerOptions).WithDefaultRedirectUri().WithParentActivityOrWindow(OSHandleUtilities.GetConsoleOrTerminalLinux);
}
}
else
{
if (!string.IsNullOrEmpty(redirectUrl))
{
builder = builder.WithRedirectUri(redirectUrl);
}
this.customWebUi = customWebUi;
}
builder.WithLegacyCacheCompatibility(false);
publicClientApplication = builder.Build();
// register tokencache if callback provided
tokenCacheCallback?.Invoke(publicClientApplication.UserTokenCache);
authenticationType = ClientContextType.AzureADInteractive;
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts through device code authentication
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="deviceCodeCallback">The callback that will be called with device code information.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, Func<DeviceCodeResult, Task> deviceCodeCallback, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) :
this(clientId, null, deviceCodeCallback, azureEnvironment, tokenCacheCallback)
{
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts through device code authentication
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="deviceCodeCallback">The callback that will be called with device code information.</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, string tenantId, Func<DeviceCodeResult, Task> deviceCodeCallback, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
this.deviceCodeCallback = deviceCodeCallback;
var builder = PublicClientApplicationBuilder.Create(clientId);
if (!string.IsNullOrEmpty(tenantId))
{
builder = builder.WithAuthority($"{azureADEndPoint}/{tenantId}/");
}
else
{
builder = builder.WithAuthority($"{azureADEndPoint}/organizations/");
}
builder = builder.WithHttpClientFactory(HttpClientFactory);
builder.WithLegacyCacheCompatibility(false);
publicClientApplication = builder.Build();
// register tokencache if callback provided
tokenCacheCallback?.Invoke(publicClientApplication.UserTokenCache);
authenticationType = ClientContextType.DeviceLogin;
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="certificate">A valid certificate</param>
/// <param name="tenantId">Tenant id or tenant url</param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, X509Certificate2 certificate, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
ConfidentialClientApplicationBuilder builder;
if (azureEnvironment != AzureEnvironment.Production)
{
builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithTenantId(tenantId).WithAuthority(azureADEndPoint, tenantId, true).WithHttpClientFactory(HttpClientFactory);
}
else
{
builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithTenantId(tenantId).WithHttpClientFactory(HttpClientFactory);
}
if (!string.IsNullOrEmpty(redirectUrl))
{
builder = builder.WithRedirectUri(redirectUrl);
}
builder.WithLegacyCacheCompatibility(false);
confidentialClientApplication = builder.Build();
// register tokencache if callback provided
tokenCacheCallback?.Invoke(confidentialClientApplication.UserTokenCache);
authenticationType = ClientContextType.AzureADCertificate;
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="certificatePath">A valid path to a certificate file</param>
/// <param name="certificatePassword">The password for the certificate</param>
/// <param name="tenantId">The tenant id (guid) or name (e.g. contoso.onmicrosoft.com) </param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, string certificatePath, string certificatePassword, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
if (System.IO.File.Exists(certificatePath))
{
ConfidentialClientApplicationBuilder builder = null;
using (var certfile = System.IO.File.OpenRead(certificatePath))
{
var certificateBytes = new byte[certfile.Length];
certfile.Read(certificateBytes, 0, (int)certfile.Length);
// Don't dispose the cert as that will lead to "m_safeCertContext is an invalid handle" errors when the confidential client actually uses the cert
#pragma warning disable CA2000 // Dispose objects before losing scope
var certificate = new X509Certificate2(certificateBytes,
certificatePassword,
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);
#pragma warning restore CA2000 // Dispose objects before losing scope
builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithTenantId(tenantId).WithHttpClientFactory(HttpClientFactory);
}
if (azureEnvironment != AzureEnvironment.Production)
{
builder.WithAuthority(azureADEndPoint, tenantId, true);
}
if (!string.IsNullOrEmpty(redirectUrl))
{
builder = builder.WithRedirectUri(redirectUrl);
}
builder.WithLegacyCacheCompatibility(false);
confidentialClientApplication = builder.Build();
// register tokencache if callback provided. ApptokenCache as AcquireTokenForClient is beind called to acquire tokens.
tokenCacheCallback?.Invoke(confidentialClientApplication.AppTokenCache);
authenticationType = ClientContextType.AzureADCertificate;
}
else
{
throw new Exception("Certificate path not found");
}
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContexts.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication</param>
/// <param name="storeName">The name of the certificate store to find the certificate in.</param>
/// <param name="storeLocation">The location of the certificate store to find the certificate in.</param>
/// <param name="thumbPrint">The thumbprint of the certificate to use.</param>
/// <param name="tenantId">The tenant id (guid) or name (e.g. contoso.onmicrosoft.com) </param>
/// <param name="redirectUrl">Optional redirect URL to use for authentication as set up in the Azure AD Application</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="tokenCacheCallback">If present, after setting up the base flow for authentication this callback will be called register a custom tokencache. See https://aka.ms/msal-net-token-cache-serialization.</param>
public AuthenticationManager(string clientId, StoreName storeName, StoreLocation storeLocation, string thumbPrint, string tenantId, string redirectUrl = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
var certificate = Utilities.X509CertificateUtility.LoadCertificate(storeName, storeLocation, thumbPrint);
var builder = ConfidentialClientApplicationBuilder.Create(clientId).WithCertificate(certificate).WithTenantId(tenantId).WithHttpClientFactory(HttpClientFactory);
builder = GetBuilderWithAuthority(builder, azureEnvironment, tenantId);
if (!string.IsNullOrEmpty(redirectUrl))
{
builder = builder.WithRedirectUri(redirectUrl);
}
if (!string.IsNullOrEmpty(tenantId))
{
builder = builder.WithTenantId(tenantId);
}
builder.WithLegacyCacheCompatibility(false);
confidentialClientApplication = builder.Build();
// register tokencache if callback provided. ApptokenCache as AcquireTokenForClient is beind called to acquire tokens.
tokenCacheCallback?.Invoke(confidentialClientApplication.AppTokenCache);
authenticationType = ClientContextType.AzureADCertificate;
}
/// <summary>
/// Creates a new instance of the Authentication Manager to acquire authenticated ClientContext.
/// </summary>
/// <param name="clientId">The client id of the Azure AD application to use for authentication.</param>
/// <param name="clientSecret">The client secret of the Azure AD application to use for authentication.</param>
/// <param name="tenantId">Optional tenant id or tenant url</param>
/// <param name="azureEnvironment">The azure environment to use. Defaults to AzureEnvironment.Production</param>
/// <param name="userAssertion">The user assertion (token) of the user on whose behalf to acquire the context</param>
/// <param name="tokenCacheCallback"></param>
public AuthenticationManager(string clientId, string clientSecret, UserAssertion userAssertion, string tenantId = null, AzureEnvironment azureEnvironment = AzureEnvironment.Production, Action<ITokenCache> tokenCacheCallback = null) : this()
{
this.azureEnvironment = azureEnvironment;
var azureADEndPoint = GetAzureADLoginEndPoint(azureEnvironment);
ConfidentialClientApplicationBuilder builder;
if (azureEnvironment != AzureEnvironment.Production)
{
if (tenantId == null)
{
throw new ArgumentException("tenantId is required", nameof(tenantId));
}
builder = ConfidentialClientApplicationBuilder.Create(clientId).WithClientSecret(clientSecret).WithAuthority(azureADEndPoint, tenantId, true).WithHttpClientFactory(HttpClientFactory);
}
else
{
builder = ConfidentialClientApplicationBuilder.Create(clientId).WithClientSecret(clientSecret).WithAuthority($"{azureADEndPoint}/organizations/").WithHttpClientFactory(HttpClientFactory);
if (!string.IsNullOrEmpty(tenantId))
{
builder = builder.WithTenantId(tenantId);
}
}
this.assertion = userAssertion;
builder.WithLegacyCacheCompatibility(false);
confidentialClientApplication = builder.Build();
// register tokencache if callback provided
tokenCacheCallback?.Invoke(confidentialClientApplication.UserTokenCache);
authenticationType = ClientContextType.AzureOnBehalfOf;
}
/// <summary>
/// Creates an AuthenticationManager for the given PnP Core SDK <see cref="IAuthenticationProvider"/>.
/// </summary>
/// <param name="authenticationProvider">PnP Core SDK <see cref="IAuthenticationProvider"/></param>
public AuthenticationManager(IAuthenticationProvider authenticationProvider)
{
this.authenticationProvider = authenticationProvider;
this.pnpContext = null;
authenticationType = ClientContextType.PnPCoreSdk;
}
/// <summary>
/// Creates an AuthenticationManager for the given PnP Core SDK
/// </summary>
/// <param name="pnPContext">PnP Core SDK<see cref="PnPContext"/></param>
public AuthenticationManager(PnPContext pnPContext)
{
this.authenticationProvider = pnPContext.AuthenticationProvider;
this.pnpContext = pnPContext;
authenticationType = ClientContextType.PnPCoreSdk;
ConfigureAuthenticationManagerEnvironmentSettings(pnPContext);
}
private void ConfigureAuthenticationManagerEnvironmentSettings(PnPContext pnPContext)
{
if (pnPContext.Environment == Microsoft365Environment.Custom)
{
this.azureEnvironment = AzureEnvironment.Custom;
this.microsoftGraphEndPoint = pnPContext.MicrosoftGraphAuthority;
this.azureADLoginEndPoint = $"https://{pnPContext.AzureADLoginAuthority}";
}
else
{
this.azureEnvironment = pnPContext.Environment switch
{
Microsoft365Environment.Production => AzureEnvironment.Production,
Microsoft365Environment.Germany => AzureEnvironment.Germany,
Microsoft365Environment.China => AzureEnvironment.China,
Microsoft365Environment.USGovernment => AzureEnvironment.USGovernment,
Microsoft365Environment.USGovernmentHigh => AzureEnvironment.USGovernmentHigh,
Microsoft365Environment.USGovernmentDoD => AzureEnvironment.USGovernmentDoD,
Microsoft365Environment.PreProduction => AzureEnvironment.PPE,
Microsoft365Environment.DelosCloud => AzureEnvironment.DelosCloud,
Microsoft365Environment.BleuCloud => AzureEnvironment.BleuCloud,
Microsoft365Environment.GovSGCloud => AzureEnvironment.GovSGCloud,
_ => AzureEnvironment.Production
};
}
}
#endregion
#region Access Token Acquisition
/// <summary>
/// Returns an access token for a given site.
/// </summary>
/// <param name="siteUrl"></param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <returns></returns>
public string GetAccessToken(string siteUrl, Prompt prompt = default)
{
return GetAccessTokenAsync(siteUrl, CancellationToken.None, prompt).GetAwaiter().GetResult();
}
/// <summary>
/// Returns an access token for a given site.
/// </summary>
/// <param name="siteUrl"></param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <returns></returns>
public async Task<string> GetAccessTokenAsync(string siteUrl, Prompt prompt = default)
{
return await GetAccessTokenAsync(siteUrl, CancellationToken.None, prompt).ConfigureAwait(false);
}
/// <summary>
/// Returns an access token for a given site.
/// </summary>
/// <param name="siteUrl"></param>
/// <param name="cancellationToken">Optional cancellation token to cancel the request</param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <returns></returns>
public string GetAccessToken(string siteUrl, CancellationToken cancellationToken, Prompt prompt = default)
{
var uri = new Uri(siteUrl);
var scopes = new[] { $"{uri.Scheme}://{uri.Authority}/.default" };
return GetAccessTokenAsync(scopes, cancellationToken, prompt, uri).GetAwaiter().GetResult();
}
/// <summary>
/// Returns an access token for a given site.
/// </summary>
/// <param name="siteUrl"></param>
/// <param name="cancellationToken">Optional cancellation token to cancel the request</param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <returns></returns>
public async Task<string> GetAccessTokenAsync(string siteUrl, CancellationToken cancellationToken, Prompt prompt = default)
{
var uri = new Uri(siteUrl);
var scopes = new[] { $"{uri.Scheme}://{uri.Authority}/.default" };
return await GetAccessTokenAsync(scopes, cancellationToken, prompt, uri).ConfigureAwait(false);
}
/// <summary>
/// Returns an access token for the given scopes.
/// </summary>
/// <param name="scopes">The scopes to retrieve the access token for</param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <returns></returns>
public async Task<string> GetAccessTokenAsync(string[] scopes, Prompt prompt = default)
{
return await GetAccessTokenAsync(scopes, CancellationToken.None, prompt).ConfigureAwait(false);
}
/// <summary>
/// Returns an access token for the given scopes.
/// </summary>
/// <param name="scopes">The scopes to retrieve the access token for</param>
/// <param name="cancellationToken">Optional cancellation token to cancel the request</param>
/// <param name="prompt">The prompt style to use. Notice that this only works with the Interactive Login flow, for all other flows this parameter is ignored.</param>
/// <param name="uri">for ClientContextType.PnPCoreSdk case as by interface definition needed for GetAccessTokenAsync</param>
/// <returns></returns>
public async Task<string> GetAccessTokenAsync(string[] scopes, CancellationToken cancellationToken, Prompt prompt = default, Uri uri = null)
{
AuthenticationResult authResult = null;
Diagnostics.Log.Debug("GetAccessTokenAsync", $"Authentication type: {authenticationType}");
switch (authenticationType)
{
case ClientContextType.AzureADCredentials:
{
var accounts = await publicClientApplication.GetAccountsAsync().ConfigureAwait(false);
try
{
authResult = await publicClientApplication.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
#pragma warning disable CS0618 // Type or member is obsolete
authResult = await publicClientApplication.AcquireTokenByUsernamePassword(scopes, username, password).ExecuteAsync(cancellationToken).ConfigureAwait(false);
#pragma warning restore CS0618 // Type or member is obsolete
}
break;
}
case ClientContextType.AzureADInteractive:
{
var accounts = await publicClientApplication.GetAccountsAsync().ConfigureAwait(false);
try
{
authResult = await publicClientApplication.AcquireTokenSilent(scopes, accounts.First()).ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
catch
{
var builder = publicClientApplication.AcquireTokenInteractive(scopes);
if (customWebUi != null)
{
builder = builder.WithCustomWebUi(customWebUi);
}
if (prompt != default)
{
builder.WithPrompt(prompt);
}
authResult = await builder.ExecuteAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
case ClientContextType.AzureADCertificate:
case ClientContextType.UserAssignedManagedIdentityFederatedCredential:
{
#pragma warning disable CS0618 // Type or member is obsolete
var accounts = await confidentialClientApplication.GetAccountsAsync().ConfigureAwait(false);
#pragma warning restore CS0618 // Type or member is obsolete