-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathEntraCP.cs
1075 lines (980 loc) · 55.5 KB
/
EntraCP.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
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 Azure.Core.Diagnostics;
using Microsoft.Graph.Models;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Claims;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Yvand.EntraClaimsProvider.Configuration;
using Yvand.EntraClaimsProvider.Logging;
using WIF4_5 = System.Security.Claims;
namespace Yvand.EntraClaimsProvider
{
public interface IClaimsProviderSettings : IEntraIDProviderSettings
{
//List<ClaimTypeConfig> RuntimeClaimTypesList { get; }
IEnumerable<ClaimTypeConfig> RuntimeMetadataConfig { get; }
IdentityClaimTypeConfig UserIdentifierClaimTypeConfig { get; }
ClaimTypeConfig GroupIdentifierClaimTypeConfig { get; }
}
public class ClaimsProviderSettings : EntraIDProviderSettings, IClaimsProviderSettings
{
public static new ClaimsProviderSettings GetDefaultSettings(string claimsProviderName)
{
EntraIDProviderSettings entraIDProviderSettings = EntraIDProviderSettings.GetDefaultSettings(claimsProviderName);
return GenerateFromEntraIDProviderSettings(entraIDProviderSettings);
}
public static ClaimsProviderSettings GenerateFromEntraIDProviderSettings(IEntraIDProviderSettings settings)
{
ClaimsProviderSettings copy = new ClaimsProviderSettings();
Utils.CopyPublicProperties(typeof(EntraIDProviderSettings), settings, copy);
return copy;
}
public List<ClaimTypeConfig> RuntimeClaimTypesList { get; set; }
public IEnumerable<ClaimTypeConfig> RuntimeMetadataConfig { get; set; }
public IdentityClaimTypeConfig UserIdentifierClaimTypeConfig { get; set; }
public ClaimTypeConfig GroupIdentifierClaimTypeConfig { get; set; }
}
public class EntraCP : SPClaimProvider
{
public static string ClaimsProviderName => "EntraCP";
public override string Name => ClaimsProviderName;
public override bool SupportsEntityInformation => true;
public override bool SupportsHierarchy => true;
public override bool SupportsResolve => true;
public override bool SupportsSearch => true;
public override bool SupportsUserKey => true;
public EntraIDEntityProvider EntityProvider { get; private set; }
private ReaderWriterLockSlim Lock_LocalConfigurationRefresh = new ReaderWriterLockSlim();
protected virtual string PickerEntityDisplayText => "({0}) {1}";
protected virtual string PickerEntityOnMouseOver => "{0}: {1}";
/// <summary>
/// Gets the settings that contain the configuration for EntraCP
/// </summary>
public IClaimsProviderSettings Settings { get; protected set; }
/// <summary>
/// Gets custom settings that will be used instead of the settings from the persisted object
/// </summary>
private IClaimsProviderSettings CustomSettings { get; }
/// <summary>
/// Gets the version of the settings, used to refresh the settings if the persisted object is updated
/// </summary>
public long SettingsVersion { get; private set; } = -1;
AzureEventSourceListener GraphEventsListener;
private SPTrustedLoginProvider _SPTrust;
/// <summary>
/// Gets the SharePoint trust that has its property ClaimProviderName equals to <see cref="Name"/>
/// </summary>
private SPTrustedLoginProvider SPTrust
{
get
{
if (this._SPTrust == null)
{
this._SPTrust = Utils.GetSPTrustAssociatedWithClaimsProvider(this.Name);
}
return this._SPTrust;
}
}
/// <summary>
/// Gets the issuer formatted to be like the property SPClaim.OriginalIssuer: "TrustedProvider:TrustedProviderName"
/// </summary>
public string OriginalIssuerName => this.SPTrust != null ? SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, this.SPTrust.Name) : String.Empty;
public EntraCP(string displayName) : base(displayName)
{
this.GraphEventsListener = new AzureEventSourceListener((args, message) =>
{
if (args.EventSource.Name == "Azure-Identity")
{
Logger.Log($"[{this.Name}] {args.EventName} {message}", Utils.EventLogToTraceSeverity(args.Level), EventSeverity.Error, TraceCategory.AzureIdentity);
}
}, EventLevel.Informational);
}
public EntraCP(string displayName, IClaimsProviderSettings customSettings) : base(displayName)
{
this.CustomSettings = customSettings;
}
#region ManageConfiguration
public static EntraIDProviderConfiguration GetConfiguration(bool initializeLocalConfiguration = false)
{
EntraIDProviderConfiguration configuration = EntraIDProviderConfiguration.GetGlobalConfiguration(new Guid(ClaimsProviderConstants.CONFIGURATION_ID), initializeLocalConfiguration);
return configuration;
}
/// <summary>
/// Creates a configuration for EntraCP. This will delete any existing configuration which may already exist
/// </summary>
/// <returns></returns>
public static EntraIDProviderConfiguration CreateConfiguration()
{
EntraIDProviderConfiguration configuration = EntraIDProviderConfiguration.CreateGlobalConfiguration(new Guid(ClaimsProviderConstants.CONFIGURATION_ID), ClaimsProviderConstants.CONFIGURATION_NAME, EntraCP.ClaimsProviderName);
return configuration;
}
/// <summary>
/// Deletes the configuration for EntraCP
/// </summary>
public static void DeleteConfiguration()
{
EntraIDProviderConfiguration configuration = EntraIDProviderConfiguration.GetGlobalConfiguration(new Guid(ClaimsProviderConstants.CONFIGURATION_ID));
if (configuration != null)
{
configuration.Delete();
}
}
#endregion
#region Initialization
/// <summary>
/// Verifies if claims provider can run in the specified <paramref name="context"/>, and if it has valid and up to date <see cref="Settings"/>.
/// </summary>
/// <param name="context">The URI of the current site, or null</param>
/// <returns>true if claims provider can run, false if it cannot continue</returns>
public bool ValidateSettings(Uri context)
{
if (!Utils.IsClaimsProviderUsedInCurrentContext(context, Name))
{
return false;
}
if (this.SPTrust == null)
{
return false;
}
bool success = true;
this.Lock_LocalConfigurationRefresh.EnterWriteLock();
try
{
IEntraIDProviderSettings settings = this.GetSettings();
if (settings == null)
{
return false;
}
if (settings.Version == this.SettingsVersion)
{
Logger.Log($"[{this.Name}] Local copy of settings is up to date with version {this.SettingsVersion}.",
TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Core);
return true;
}
this.Settings = ClaimsProviderSettings.GenerateFromEntraIDProviderSettings(settings);
Logger.Log($"[{this.Name}] Settings have new version {this.Settings.Version}, refreshing local copy",
TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Core);
success = this.InitializeInternalRuntimeSettings();
if (success)
{
#if !DEBUGx
this.SettingsVersion = this.Settings.Version;
#endif
this.EntityProvider = new EntraIDEntityProvider(Name, this.Settings);
}
}
catch (Exception ex)
{
success = false;
Logger.LogException(Name, "while refreshing configuration", TraceCategory.Core, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitWriteLock();
}
return success;
}
/// <summary>
/// Returns the settings to use
/// </summary>
/// <returns></returns>
public virtual IEntraIDProviderSettings GetSettings()
{
if (this.CustomSettings != null)
{
return this.CustomSettings;
}
IEntraIDProviderSettings persistedSettings = null;
EntraIDProviderConfiguration PersistedConfiguration = EntraIDProviderConfiguration.GetGlobalConfiguration(new Guid(ClaimsProviderConstants.CONFIGURATION_ID));
if (PersistedConfiguration != null)
{
persistedSettings = PersistedConfiguration.Settings;
}
return persistedSettings;
}
/// <summary>
/// Sets the internal runtime settings properties
/// </summary>
/// <returns>True if successful, false if not</returns>
private bool InitializeInternalRuntimeSettings()
{
ClaimsProviderSettings settings = (ClaimsProviderSettings)this.Settings;
if (settings.ClaimTypes?.Count <= 0)
{
Logger.Log($"[{this.Name}] Cannot continue because configuration has 0 claim configured.",
TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Core);
return false;
}
bool identityClaimTypeFound = false;
bool groupClaimTypeFound = false;
List<ClaimTypeConfig> claimTypesSetInTrust = new List<ClaimTypeConfig>();
// Parse the ClaimTypeInformation collection set in the SPTrustedLoginProvider
foreach (SPTrustedClaimTypeInformation claimTypeInformation in this.SPTrust.ClaimTypeInformation)
{
// Search if current claim type in trust exists in ClaimTypeConfigCollection
ClaimTypeConfig claimTypeConfig = settings.ClaimTypes.FirstOrDefault(x =>
String.Equals(x.ClaimType, claimTypeInformation.MappedClaimType, StringComparison.InvariantCultureIgnoreCase) &&
!x.UseMainClaimTypeOfDirectoryObject &&
x.EntityProperty != DirectoryObjectProperty.NotSet);
if (claimTypeConfig == null)
{
continue;
}
ClaimTypeConfig localClaimTypeConfig = claimTypeConfig.CopyConfiguration();
localClaimTypeConfig.ClaimTypeDisplayName = claimTypeInformation.DisplayName;
claimTypesSetInTrust.Add(localClaimTypeConfig);
if (String.Equals(this.SPTrust.IdentityClaimTypeInformation.MappedClaimType, localClaimTypeConfig.ClaimType, StringComparison.InvariantCultureIgnoreCase))
{
// Identity claim type found, set IdentityClaimTypeConfig property
identityClaimTypeFound = true;
settings.UserIdentifierClaimTypeConfig = IdentityClaimTypeConfig.ConvertClaimTypeConfig(localClaimTypeConfig);
}
else if (!groupClaimTypeFound && localClaimTypeConfig.EntityType == DirectoryObjectType.Group)
{
groupClaimTypeFound = true;
settings.GroupIdentifierClaimTypeConfig = localClaimTypeConfig;
}
}
if (!identityClaimTypeFound)
{
Logger.Log($"[{this.Name}] Cannot continue because identity claim type '{this.SPTrust.IdentityClaimTypeInformation.MappedClaimType}' set in the SPTrustedIdentityTokenIssuer '{SPTrust.Name}' is missing in the ClaimTypeConfig list.", TraceSeverity.Unexpected, EventSeverity.ErrorCritical, TraceCategory.Core);
return false;
}
// Check if there are additional properties to use in queries (UseMainClaimTypeOfDirectoryObject set to true)
List<ClaimTypeConfig> additionalClaimTypeConfigList = new List<ClaimTypeConfig>();
foreach (ClaimTypeConfig claimTypeConfig in settings.ClaimTypes.Where(x => x.UseMainClaimTypeOfDirectoryObject))
{
ClaimTypeConfig localClaimTypeConfig = claimTypeConfig.CopyConfiguration();
if (localClaimTypeConfig.EntityType == DirectoryObjectType.User)
{
localClaimTypeConfig.ClaimType = settings.UserIdentifierClaimTypeConfig.ClaimType;
localClaimTypeConfig.EntityPropertyToUseAsDisplayText = settings.UserIdentifierClaimTypeConfig.EntityPropertyToUseAsDisplayText;
}
else
{
// If not a user, it must be a group
if (settings.GroupIdentifierClaimTypeConfig == null)
{
continue;
}
localClaimTypeConfig.ClaimType = settings.GroupIdentifierClaimTypeConfig.ClaimType;
localClaimTypeConfig.EntityPropertyToUseAsDisplayText = settings.GroupIdentifierClaimTypeConfig.EntityPropertyToUseAsDisplayText;
localClaimTypeConfig.ClaimTypeDisplayName = settings.GroupIdentifierClaimTypeConfig.ClaimTypeDisplayName;
}
additionalClaimTypeConfigList.Add(localClaimTypeConfig);
}
settings.RuntimeClaimTypesList = new List<ClaimTypeConfig>(claimTypesSetInTrust.Count + additionalClaimTypeConfigList.Count);
settings.RuntimeClaimTypesList.AddRange(claimTypesSetInTrust);
settings.RuntimeClaimTypesList.AddRange(additionalClaimTypeConfigList);
// Get all PickerEntity metadata with a DirectoryObjectProperty set
settings.RuntimeMetadataConfig = settings.ClaimTypes.Where(x =>
!String.IsNullOrWhiteSpace(x.EntityDataKey) &&
x.EntityProperty != DirectoryObjectProperty.NotSet);
if (settings.EntraIDTenants == null || settings.EntraIDTenants.Count < 1)
{
return false;
}
// Initialize Graph client on each tenant
foreach (var tenant in settings.EntraIDTenants)
{
tenant.InitializeAuthentication(settings.Timeout, settings.ProxyAddress);
}
this.Settings = settings;
return true;
}
#endregion
#region Augmentation
protected override void FillClaimsForEntity(Uri context, SPClaim entity, List<SPClaim> claims)
{
AugmentEntity(context, entity, null, claims);
}
protected override void FillClaimsForEntity(Uri context, SPClaim entity, SPClaimProviderContext claimProviderContext, List<SPClaim> claims)
{
AugmentEntity(context, entity, claimProviderContext, claims);
}
/// <summary>
/// Gets the group membership of the <paramref name="entity"/> and add it to the list of <paramref name="claims"/>
/// </summary>
/// <param name="context"></param>
/// <param name="entity">entity to augment</param>
/// <param name="claimProviderContext">Can be null</param>
/// <param name="claims"></param>
protected void AugmentEntity(Uri context, SPClaim entity, SPClaimProviderContext claimProviderContext, List<SPClaim> claims)
{
SPClaim decodedEntity;
if (SPClaimProviderManager.IsUserIdentifierClaim(entity))
{
decodedEntity = SPClaimProviderManager.DecodeUserIdentifierClaim(entity);
}
else
{
if (SPClaimProviderManager.IsEncodedClaim(entity.Value))
{
decodedEntity = SPClaimProviderManager.Local.DecodeClaim(entity.Value);
}
else
{
decodedEntity = entity;
}
}
SPOriginalIssuerType loginType = SPOriginalIssuers.GetIssuerType(decodedEntity.OriginalIssuer);
if (loginType != SPOriginalIssuerType.TrustedProvider && loginType != SPOriginalIssuerType.ClaimProvider)
{
Logger.Log($"[{Name}] Not trying to augment '{decodedEntity.Value}' because his OriginalIssuer is '{decodedEntity.OriginalIssuer}'.",
TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Augmentation);
return;
}
using (new SPMonitoredScope($"[{ClaimsProviderName}] Augmentation for user \"{decodedEntity.Value}", 3000))
{
if (!ValidateSettings(context)) { return; }
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
// There can be multiple TrustedProvider on the farm, but EntraCP should only do augmentation if current entity is from TrustedProvider it is associated with
if (!String.Equals(decodedEntity.OriginalIssuer, this.OriginalIssuerName, StringComparison.InvariantCultureIgnoreCase)) { return; }
if (!this.Settings.EnableAugmentation) { return; }
if (Settings.GroupIdentifierClaimTypeConfig == null)
{
Logger.Log($"[{Name}] No claim type with EntityType 'Group' was found, please check claims mapping table.",
TraceSeverity.High, EventSeverity.Error, TraceCategory.Augmentation);
return;
}
Logger.Log($"[{Name}] Starting augmentation for user '{decodedEntity.Value}'.", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Augmentation);
OperationContext currentContext = new OperationContext(this.Settings as ClaimsProviderSettings, OperationType.Augmentation, null, decodedEntity, context, null, null, Int32.MaxValue);
Stopwatch timer = new Stopwatch();
timer.Start();
Task<List<string>> groupsTask = this.EntityProvider.GetEntityGroupsAsync(currentContext);
groupsTask.ConfigureAwait(false);
groupsTask.Wait(this.Settings.Timeout);
List<string> groups = groupsTask.Result;
timer.Stop();
if (groups?.Count > 0)
{
foreach (string group in groups)
{
claims.Add(CreateClaim(Settings.GroupIdentifierClaimTypeConfig.ClaimType, group, Settings.GroupIdentifierClaimTypeConfig.ClaimValueType));
Logger.Log($"[{Name}] Added group '{group}' to user '{currentContext.IncomingEntity.Value}'",
TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Augmentation);
}
Logger.Log($"[{Name}] Augmented user '{currentContext.IncomingEntity.Value}' with {groups.Count} groups in {timer.ElapsedMilliseconds} ms",
TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Augmentation);
}
else
{
Logger.Log($"[{Name}] Got no group in {timer.ElapsedMilliseconds} ms for user '{currentContext.IncomingEntity.Value}'",
TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Augmentation);
}
}
catch (Exception ex)
{
Logger.LogException(Name, "in AugmentEntity", TraceCategory.Augmentation, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
}
#endregion
#region Search
protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List<PickerEntity> resolved)
{
if (!ValidateSettings(context)) { return; }
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
OperationContext currentContext = new OperationContext(this.Settings as ClaimsProviderSettings, OperationType.Search, resolveInput, null, context, entityTypes, null, 30);
List<PickerEntity> entities = SearchOrValidate(currentContext);
if (entities == null || entities.Count == 0) { return; }
foreach (PickerEntity entity in entities)
{
resolved.Add(entity);
Logger.Log($"[{Name}] Added entity: display text: '{entity.DisplayText}', claim value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}'",
TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Claims_Picking);
}
Logger.Log($"[{Name}] Returned {entities.Count} entities with value '{currentContext.Input}'", TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Claims_Picking);
}
catch (Exception ex)
{
Logger.LogException(Name, "in FillResolve(string)", TraceCategory.Claims_Picking, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
protected override void FillSearch(Uri context, string[] entityTypes, string searchPattern, string hierarchyNodeID, int maxCount, SPProviderHierarchyTree searchTree)
{
if (!ValidateSettings(context)) { return; }
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
OperationContext currentContext = new OperationContext(this.Settings as ClaimsProviderSettings, OperationType.Search, searchPattern, null, context, entityTypes, hierarchyNodeID, maxCount);
List<PickerEntity> entities = this.SearchOrValidate(currentContext);
if (entities == null || entities.Count == 0) { return; }
SPProviderHierarchyNode matchNode = null;
foreach (PickerEntity entity in entities)
{
// Add current PickerEntity to the corresponding ClaimType in the hierarchy
if (searchTree.HasChild(entity.Claim.ClaimType))
{
matchNode = searchTree.Children.First(x => x.HierarchyNodeID == entity.Claim.ClaimType);
}
else
{
ClaimTypeConfig ctConfig = currentContext.CurrentClaimTypeConfigList.FirstOrDefault(x =>
!x.UseMainClaimTypeOfDirectoryObject &&
String.Equals(x.ClaimType, entity.Claim.ClaimType, StringComparison.InvariantCultureIgnoreCase));
string nodeName = ctConfig != null ? ctConfig.ClaimTypeDisplayName : entity.Claim.ClaimType;
matchNode = new SPProviderHierarchyNode(Name, nodeName, entity.Claim.ClaimType, true);
searchTree.AddChild(matchNode);
}
matchNode.AddEntity(entity);
Logger.Log($"[{Name}] Added entity: display text: '{entity.DisplayText}', claim value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}'",
TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Claims_Picking);
}
Logger.Log($"[{Name}] Returned {entities.Count} entities from value '{currentContext.Input}'",
TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Claims_Picking);
}
catch (Exception ex)
{
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
#endregion
#region Validation
protected override void FillResolve(Uri context, string[] entityTypes, SPClaim resolveInput, List<PickerEntity> resolved)
{
if (!ValidateSettings(context)) { return; }
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
// Ensure incoming claim should be validated by EntraCP
// Must be made after call to Initialize because SPTrustedLoginProvider name must be known
if (!String.Equals(resolveInput.OriginalIssuer, this.OriginalIssuerName, StringComparison.InvariantCultureIgnoreCase)) { return; }
OperationContext currentContext = new OperationContext(this.Settings as ClaimsProviderSettings, OperationType.Validation, resolveInput.Value, resolveInput, context, entityTypes, null, 1);
List<PickerEntity> entities = this.SearchOrValidate(currentContext);
if (entities?.Count == 1)
{
resolved.Add(entities[0]);
Logger.Log($"[{Name}] Validated entity: display text: '{entities[0].DisplayText}', claim value: '{entities[0].Claim.Value}', claim type: '{entities[0].Claim.ClaimType}'",
TraceSeverity.High, EventSeverity.Information, TraceCategory.Claims_Picking);
}
else
{
int entityCount = entities == null ? 0 : entities.Count;
Logger.Log($"[{Name}] Validation failed: found {entityCount.ToString()} entities instead of 1 for incoming claim with value '{currentContext.IncomingEntity.Value}' and type '{currentContext.IncomingEntity.ClaimType}'", TraceSeverity.Unexpected, EventSeverity.Error, TraceCategory.Claims_Picking);
}
}
catch (Exception ex)
{
Logger.LogException(Name, "in FillResolve(SPClaim)", TraceCategory.Claims_Picking, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
#endregion
#region ProcessSearchOrValidation
/// <summary>
/// Search spEntities, or validate 1 entity, depending on <paramref name="currentContext"/>
/// </summary>
/// <param name="currentContext">Information about current context and operation</param>
/// <returns>Entities generated by EntraCP</returns>
protected List<PickerEntity> SearchOrValidate(OperationContext currentContext)
{
List<DirectoryObject> azureADEntityList = null;
List<PickerEntity> pickerEntityList = new List<PickerEntity>();
try
{
if (this.Settings.AlwaysResolveUserInput)
{
// Completely bypass query to Microsoft Entra ID
pickerEntityList = CreatePickerEntityForSpecificClaimTypes(
currentContext.Input,
currentContext.CurrentClaimTypeConfigList.FindAll(x => !x.UseMainClaimTypeOfDirectoryObject));
Logger.Log($"[{Name}] Created {pickerEntityList.Count} entity(ies) without contacting Microsoft Entra ID tenant(s) because EntraCP property AlwaysResolveUserInput is set to true.",
TraceSeverity.Medium, EventSeverity.Information, TraceCategory.Claims_Picking);
return pickerEntityList;
}
// Create a delegate to query Entra ID, so it is called only if needed
Func<Task> SearchOrValidateInEntraID = delegate ()
{
return Task.Run(async () =>
{
using (new SPMonitoredScope($"[{Name}] Total time spent to query Microsoft Entra ID tenant(s)", 1000))
{
azureADEntityList = await this.EntityProvider.SearchOrValidateEntitiesAsync(currentContext).ConfigureAwait(false);
}
});
};
if (currentContext.OperationType == OperationType.Search)
{
// Between 0 to many PickerEntity is expected by SharePoint
// Check if value starts with a prefix configured on a ClaimTypeConfig. If so an entity should be returned using ClaimTypeConfig found
// ClaimTypeConfigEnsureUniquePrefixToBypassLookup ensures that collection cannot contain duplicates
ClaimTypeConfig ctConfigWithInputPrefixMatch = currentContext.CurrentClaimTypeConfigList.FirstOrDefault(x =>
!String.IsNullOrEmpty(x.PrefixToBypassLookup) &&
currentContext.Input.StartsWith(x.PrefixToBypassLookup, StringComparison.InvariantCultureIgnoreCase));
if (ctConfigWithInputPrefixMatch != null)
{
string inputWithoutPrefix = currentContext.Input.Substring(ctConfigWithInputPrefixMatch.PrefixToBypassLookup.Length);
if (String.IsNullOrEmpty(inputWithoutPrefix))
{
// No value in the value after the prefix, return
return pickerEntityList;
}
pickerEntityList = CreatePickerEntityForSpecificClaimTypes(
inputWithoutPrefix,
new List<ClaimTypeConfig>() { ctConfigWithInputPrefixMatch });
if (pickerEntityList?.Count == 1)
{
PickerEntity entity = pickerEntityList.FirstOrDefault();
Logger.Log($"[{Name}] Created entity without contacting Microsoft Entra ID tenant(s) because value started with prefix '{ctConfigWithInputPrefixMatch.PrefixToBypassLookup}', which is configured for claim type '{ctConfigWithInputPrefixMatch.ClaimType}'. Claim value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}'",
TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
}
}
else
{
// Call async method in a task to avoid error "Asynchronous operations are not allowed in this context" error when permission is validated (POST from people picker)
// More info on the error: https://stackoverflow.com/questions/672237/running-an-asynchronous-operation-triggered-by-an-asp-net-web-page-request
Task.Run(async () => await SearchOrValidateInEntraID()).Wait();
if (azureADEntityList?.Count > 0)
{
pickerEntityList = this.ProcessAzureADResults(currentContext, azureADEntityList);
}
}
}
else if (currentContext.OperationType == OperationType.Validation)
{
// Exactly 1 PickerEntity is expected by SharePoint
// Check if config corresponding to current claim type has a config to bypass Entra ID
if (!String.IsNullOrWhiteSpace(currentContext.CurrentClaimTypeConfigList.First().PrefixToBypassLookup))
{
// At this stage, it is impossible to know if entity was originally created with the keyword that bypass query to Microsoft Entra ID
// But it should be always validated since property PrefixToBypassLookup is set for current ClaimTypeConfig, so create entity manually
pickerEntityList = CreatePickerEntityForSpecificClaimTypes(
currentContext.IncomingEntity.Value,
currentContext.CurrentClaimTypeConfigList);
if (pickerEntityList?.Count == 1)
{
PickerEntity entity = pickerEntityList.FirstOrDefault();
Logger.Log($"[{Name}] Validated entity without contacting Microsoft Entra ID tenant(s) because its claim type ('{currentContext.CurrentClaimTypeConfigList.First().ClaimType}') has property 'PrefixToBypassLookup' set in EntraCPConfig.ClaimTypes. Claim value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}'",
TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
}
}
else
{
// Call async method in a task to avoid error "Asynchronous operations are not allowed in this context" error when permission is validated (POST from people picker)
// More info on the error: https://stackoverflow.com/questions/672237/running-an-asynchronous-operation-triggered-by-an-asp-net-web-page-request
Task.Run(async () => await SearchOrValidateInEntraID()).Wait();
if (azureADEntityList?.Count == 1)
{
pickerEntityList = this.ProcessAzureADResults(currentContext, azureADEntityList);
}
}
}
}
catch (Exception ex)
{
Logger.LogException(Name, "in SearchOrValidate", TraceCategory.Claims_Picking, ex);
}
pickerEntityList = this.InspectEntitiesFound(currentContext, pickerEntityList);
return pickerEntityList;
}
/// <summary>
/// Override this method to inspect the spEntities generated by EntraCP during a search or a validation operation, and add or remove spEntities
/// </summary>
/// <param name="currentContext">Information about current context and operation</param>
/// <param name="entities">Entities generated by EntraCP</param>
/// <returns>Final list of spEntities that EntraCP will return to SharePoint</returns>
protected virtual List<PickerEntity> InspectEntitiesFound(OperationContext currentContext, List<PickerEntity> entities)
{
return entities;
}
private List<PickerEntity> ProcessAzureADResults(OperationContext currentContext, List<DirectoryObject> usersAndGroups)
{
if (usersAndGroups == null || !usersAndGroups.Any())
{
return null;
};
List<ClaimTypeConfig> ctConfigs = currentContext.CurrentClaimTypeConfigList;
//Really?
//if (currentContext.ExactSearch)
//{
// ctConfigs = currentContext.CurrentClaimTypeConfigList.FindAll(x => !x.UseMainClaimTypeOfDirectoryObject);
//}
List<PickerEntity> spEntities = new List<PickerEntity>();
List<ClaimsProviderEntity> uniqueDirectoryResults = new List<ClaimsProviderEntity>();
foreach (DirectoryObject userOrGroup in usersAndGroups)
{
DirectoryObject currentObject = null;
DirectoryObjectType objectType;
if (userOrGroup is User)
{
currentObject = userOrGroup;
objectType = DirectoryObjectType.User;
}
else
{
currentObject = userOrGroup;
objectType = DirectoryObjectType.Group;
// No longer necessary since now it is handled directly when building the filter for Graph
//if (this.Settings.FilterSecurityEnabledGroupsOnly)
//{
// Group group = (Group)userOrGroup;
// bool isSecurityEnabled = group.SecurityEnabled ?? false;
// if (!isSecurityEnabled)
// {
// continue;
// }
//}
}
foreach (ClaimTypeConfig ctConfig in ctConfigs.Where(x => x.EntityType == objectType))
{
// Get value with of current GraphProperty
string directoryObjectPropertyValue = Utils.GetDirectoryObjectPropertyValue(currentObject, ctConfig.EntityProperty.ToString());
if (ctConfig is IdentityClaimTypeConfig)
{
if (String.Equals(((User)currentObject).UserType, ClaimsProviderConstants.GUEST_USERTYPE, StringComparison.InvariantCultureIgnoreCase))
{
// For Guest users, use the value set in property DirectoryObjectPropertyForGuestUsers
directoryObjectPropertyValue = Utils.GetDirectoryObjectPropertyValue(currentObject, ((IdentityClaimTypeConfig)ctConfig).DirectoryObjectPropertyForGuestUsers.ToString());
}
}
// Check if property exists (not null) and has a value (not String.Empty)
if (String.IsNullOrEmpty(directoryObjectPropertyValue)) { continue; }
// Check if current value mathes value, otherwise go to next GraphProperty to check
if (currentContext.ExactSearch)
{
if (!String.Equals(directoryObjectPropertyValue, currentContext.Input, StringComparison.InvariantCultureIgnoreCase)) { continue; }
}
else
{
if (!directoryObjectPropertyValue.StartsWith(currentContext.Input, StringComparison.InvariantCultureIgnoreCase)) { continue; }
}
// Current DirectoryObjectProperty value matches user value. Add current result to search results if it is not already present
string entityClaimValue = directoryObjectPropertyValue;
ClaimTypeConfig claimTypeConfigToCompare;
if (ctConfig.UseMainClaimTypeOfDirectoryObject)
{
if (objectType == DirectoryObjectType.User)
{
claimTypeConfigToCompare = this.Settings.UserIdentifierClaimTypeConfig;
if (String.Equals(((User)currentObject).UserType, ClaimsProviderConstants.GUEST_USERTYPE, StringComparison.InvariantCultureIgnoreCase))
{
// For Guest users, use the value set in property DirectoryObjectPropertyForGuestUsers
entityClaimValue = Utils.GetDirectoryObjectPropertyValue(currentObject, this.Settings.UserIdentifierClaimTypeConfig.DirectoryObjectPropertyForGuestUsers.ToString());
}
else
{
// Get the value of the DirectoryObjectProperty linked to current directory object
entityClaimValue = Utils.GetDirectoryObjectPropertyValue(currentObject, claimTypeConfigToCompare.EntityProperty.ToString());
}
}
else
{
claimTypeConfigToCompare = this.Settings.GroupIdentifierClaimTypeConfig;
// Get the value of the DirectoryObjectProperty linked to current directory object
entityClaimValue = Utils.GetDirectoryObjectPropertyValue(currentObject, claimTypeConfigToCompare.EntityProperty.ToString());
}
if (String.IsNullOrEmpty(entityClaimValue)) { continue; }
}
else
{
claimTypeConfigToCompare = ctConfig;
}
// if claim type and claim value already exists, skip
bool resultAlreadyExists = uniqueDirectoryResults.Exists(x =>
String.Equals(x.ClaimTypeConfigMatch.ClaimType, claimTypeConfigToCompare.ClaimType, StringComparison.InvariantCultureIgnoreCase) &&
String.Equals(x.PermissionValue, entityClaimValue, StringComparison.InvariantCultureIgnoreCase));
if (resultAlreadyExists) { continue; }
// Passed the checks, add it to the uniqueDirectoryResults list
ClaimsProviderEntity claimsProviderEntity = new ClaimsProviderEntity(currentObject, ctConfig, entityClaimValue, directoryObjectPropertyValue);
spEntities.Add(CreatePickerEntityHelper(currentContext, claimsProviderEntity));
uniqueDirectoryResults.Add(claimsProviderEntity);
}
}
Logger.Log($"[{Name}] Created {spEntities.Count} entity(ies) after filtering directory results", TraceSeverity.Verbose, EventSeverity.Information, TraceCategory.Lookup);
return spEntities;
}
#endregion
#region Helpers
protected PickerEntity CreatePickerEntityHelper(OperationContext currentContext, ClaimsProviderEntity result)
{
ClaimTypeConfig directoryObjectIdentifierConfig = result.ClaimTypeConfigMatch;
if (result.ClaimTypeConfigMatch.UseMainClaimTypeOfDirectoryObject)
{
// Get the config to use to create the actual entity (claim type and its DirectoryObjectAttribute) from current result
directoryObjectIdentifierConfig = result.ClaimTypeConfigMatch.EntityType == DirectoryObjectType.User ? this.Settings.UserIdentifierClaimTypeConfig : this.Settings.GroupIdentifierClaimTypeConfig;
}
string permissionValue = FormatPermissionValue(result.PermissionValue);
SPClaim claim = CreateClaim(directoryObjectIdentifierConfig.ClaimType, permissionValue, directoryObjectIdentifierConfig.ClaimValueType);
PickerEntity entity = CreatePickerEntity();
entity.Claim = claim;
entity.EntityType = directoryObjectIdentifierConfig.SharePointEntityType;
if (String.IsNullOrWhiteSpace(entity.EntityType))
{
entity.EntityType = directoryObjectIdentifierConfig.EntityType == DirectoryObjectType.User ? SPClaimEntityTypes.User : ClaimsProviderConstants.GroupClaimEntityType;
}
entity.IsResolved = true;
entity.EntityGroupName = this.Name;
entity.Description = String.Format(PickerEntityOnMouseOver, result.ClaimTypeConfigMatch.EntityProperty.ToString(), result.DirectoryObjectPropertyValueMatch);
entity.DisplayText = FormatPermissionDisplayText(result.DirectoryEntity, directoryObjectIdentifierConfig, permissionValue);
int nbMetadata = 0;
// Populate the metadata for this PickerEntity
// Populate metadata of new PickerEntity
foreach (ClaimTypeConfig ctConfig in this.Settings.RuntimeMetadataConfig.Where(x => x.EntityType == result.ClaimTypeConfigMatch.EntityType))
{
// if there is actally a value in the GraphObject, then it can be set
string entityAttribValue = Utils.GetDirectoryObjectPropertyValue(result.DirectoryEntity, ctConfig.EntityProperty.ToString());
if (!String.IsNullOrEmpty(entityAttribValue))
{
entity.EntityData[ctConfig.EntityDataKey] = entityAttribValue;
nbMetadata++;
Logger.Log($"[{Name}] Set metadata '{ctConfig.EntityDataKey}' of new entity to '{entityAttribValue}'", TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
}
}
Logger.Log($"[{Name}] Created entity: display text: '{entity.DisplayText}', claim value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}', and filled with {nbMetadata} metadata.", TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
return entity;
}
private List<PickerEntity> CreatePickerEntityForSpecificClaimTypes(string claimValue, List<ClaimTypeConfig> ctConfigs)
{
List<PickerEntity> entities = new List<PickerEntity>();
foreach (var ctConfig in ctConfigs)
{
SPClaim claim = CreateClaim(ctConfig.ClaimType, claimValue, ctConfig.ClaimValueType);
PickerEntity entity = CreatePickerEntity();
entity.Claim = claim;
entity.IsResolved = true;
entity.EntityType = ctConfig.SharePointEntityType;
if (String.IsNullOrWhiteSpace(entity.EntityType))
{
entity.EntityType = ctConfig.EntityType == DirectoryObjectType.User ? SPClaimEntityTypes.User : ClaimsProviderConstants.GroupClaimEntityType;
}
entity.EntityGroupName = this.Name;
entity.Description = String.Format(PickerEntityOnMouseOver, ctConfig.EntityProperty.ToString(), claimValue);
entity.DisplayText = FormatPermissionDisplayText(null, ctConfig, claimValue);
if (!String.IsNullOrWhiteSpace(ctConfig.EntityDataKey))
{
entity.EntityData[ctConfig.EntityDataKey] = entity.Claim.Value;
Logger.Log($"[{Name}] Added metadata '{ctConfig.EntityDataKey}' with value '{entity.EntityData[ctConfig.EntityDataKey]}' to new entity", TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
}
entities.Add(entity);
Logger.Log($"[{Name}] Created entity: display text: '{entity.DisplayText}', value: '{entity.Claim.Value}', claim type: '{entity.Claim.ClaimType}'.", TraceSeverity.VerboseEx, EventSeverity.Information, TraceCategory.Claims_Picking);
}
return entities.Count > 0 ? entities : null;
}
protected virtual string FormatPermissionValue(string claimValue)
{
return claimValue;
}
protected virtual string FormatPermissionDisplayText(DirectoryObject directoryResult, ClaimTypeConfig associatedClaimTypeConfig, string claimValue)
{
bool isUserIdentityClaimType = String.Equals(associatedClaimTypeConfig.ClaimType, this.Settings.UserIdentifierClaimTypeConfig.ClaimType, StringComparison.InvariantCultureIgnoreCase);
string entityDisplayText = this.Settings.EntityDisplayTextPrefix;
if (directoryResult == null)
{
if (isUserIdentityClaimType)
{
entityDisplayText += claimValue;
}
else
{
entityDisplayText += String.Format(PickerEntityDisplayText, associatedClaimTypeConfig.ClaimTypeDisplayName, claimValue);
}
}
else
{
string leadingTokenValue = String.Empty;
string directoryValueInDisplayText = claimValue;
if (associatedClaimTypeConfig.EntityPropertyToUseAsDisplayText != DirectoryObjectProperty.NotSet)
{
directoryValueInDisplayText = Utils.GetDirectoryObjectPropertyValue(directoryResult, associatedClaimTypeConfig.EntityPropertyToUseAsDisplayText.ToString());
}
directoryValueInDisplayText = leadingTokenValue + directoryValueInDisplayText;
if (!isUserIdentityClaimType)
{
entityDisplayText += String.Format(PickerEntityDisplayText, associatedClaimTypeConfig.ClaimTypeDisplayName, directoryValueInDisplayText);
}
else
{
entityDisplayText += directoryValueInDisplayText;
}
}
return entityDisplayText;
}
protected virtual new SPClaim CreateClaim(string type, string value, string valueType)
{
// SPClaimProvider.CreateClaim sets property OriginalIssuer to SPOriginalIssuerType.ClaimProvider, which is not correct
//return CreateClaim(type, value, valueType);
return new SPClaim(type, value, valueType, this.OriginalIssuerName);
}
#endregion
protected override void FillSchema(SPProviderSchema schema)
{
schema.AddSchemaElement(new SPSchemaElement(PeopleEditorEntityDataKeys.DisplayName, "Display Name", SPSchemaElementType.Both));
}
protected override void FillClaimTypes(List<string> claimTypes)
{
if (claimTypes == null) { return; }
bool configIsValid = ValidateSettings(null);
if (configIsValid)
{
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
foreach (var claimTypeSettings in ((ClaimsProviderSettings)this.Settings).RuntimeClaimTypesList)
{
claimTypes.Add(claimTypeSettings.ClaimType);
}
}
catch (Exception ex)
{
Logger.LogException(Name, "in FillClaimTypes", TraceCategory.Core, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
}
protected override void FillClaimValueTypes(List<string> claimValueTypes)
{
claimValueTypes.Add(WIF4_5.ClaimValueTypes.String);
}
protected override void FillEntityTypes(List<string> entityTypes)
{
entityTypes.Add(SPClaimEntityTypes.User);
entityTypes.Add(ClaimsProviderConstants.GroupClaimEntityType);
}
protected override void FillHierarchy(Uri context, string[] entityTypes, string hierarchyNodeID, int numberOfLevels, SPProviderHierarchyTree hierarchy)
{
List<DirectoryObjectType> aadEntityTypes = new List<DirectoryObjectType>();
if (entityTypes.Contains(SPClaimEntityTypes.User)) { aadEntityTypes.Add(DirectoryObjectType.User); }
if (entityTypes.Contains(ClaimsProviderConstants.GroupClaimEntityType)) { aadEntityTypes.Add(DirectoryObjectType.Group); }
if (!ValidateSettings(context)) { return; }
this.Lock_LocalConfigurationRefresh.EnterReadLock();
try
{
if (hierarchyNodeID == null)
{
// Root level
foreach (var azureObject in ((ClaimsProviderSettings)this.Settings).RuntimeClaimTypesList.FindAll(x => !x.UseMainClaimTypeOfDirectoryObject && aadEntityTypes.Contains(x.EntityType)))
{
hierarchy.AddChild(
new Microsoft.SharePoint.WebControls.SPProviderHierarchyNode(
Name,
azureObject.ClaimTypeDisplayName,
azureObject.ClaimType,
true));
}
}
}
catch (Exception ex)
{
Logger.LogException(Name, "in FillHierarchy", TraceCategory.Claims_Picking, ex);
}
finally
{
this.Lock_LocalConfigurationRefresh.ExitReadLock();
}
}
/// <summary>
/// Return the identity claim type
/// </summary>
/// <returns></returns>
public override string GetClaimTypeForUserKey()
{
try
{
return this.SPTrust != null ? this.SPTrust.IdentityClaimTypeInformation.MappedClaimType : String.Empty;
}
catch (Exception ex)
{
Logger.LogException(Name, "in GetClaimTypeForUserKey", TraceCategory.Rehydration, ex);
}
return String.Empty;
}
/// <summary>
/// Return the user key (SPClaim with identity claim type) from the incoming entity
/// </summary>
/// <param name="entity"></param>