-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ClaimsIdentity.cs
1357 lines (1181 loc) · 49.2 KB
/
ClaimsIdentity.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
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>Microsoft</OWNER>
//
//
// ClaimsIdentity.cs
//
namespace System.Security.Claims
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
using System.Security.Principal;
/// <summary>
/// An Identity that is represented by a set of claims.
/// </summary>
[Serializable]
[ComVisible(true)]
public class ClaimsIdentity : IIdentity
{
private enum SerializationMask
{
None = 0,
AuthenticationType = 1,
BootstrapConext = 2,
NameClaimType = 4,
RoleClaimType = 8,
HasClaims = 16,
HasLabel = 32,
Actor = 64,
UserData = 128,
}
[NonSerialized]
private byte[] m_userSerializationData;
[NonSerialized]
const string PreFix = "System.Security.ClaimsIdentity.";
[NonSerialized]
const string ActorKey = PreFix + "actor";
[NonSerialized]
const string AuthenticationTypeKey = PreFix + "authenticationType";
[NonSerialized]
const string BootstrapContextKey = PreFix + "bootstrapContext";
[NonSerialized]
const string ClaimsKey = PreFix + "claims";
[NonSerialized]
const string LabelKey = PreFix + "label";
[NonSerialized]
const string NameClaimTypeKey = PreFix + "nameClaimType";
[NonSerialized]
const string RoleClaimTypeKey = PreFix + "roleClaimType";
[NonSerialized]
const string VersionKey = PreFix + "version";
[NonSerialized]
public const string DefaultIssuer = @"LOCAL AUTHORITY";
[NonSerialized]
public const string DefaultNameClaimType = ClaimTypes.Name;
[NonSerialized]
public const string DefaultRoleClaimType = ClaimTypes.Role;
// === Important
//
// adding claims to this list will affect the Authorization for this Identity
// originally marked this as SecurityCritical, however because enumerators access it
// we would need to extend SecuritySafeCritical to the enumerator methods AND the constructors.
// In the end, this requires additional [SecuritySafeCritical] attributes. So if any additional access
// is added to 'm_instanceClaims' then this must be carefully monitored. This is equivalent to adding sids to the
// NTToken and will be used up the stack to make Authorization decisions.
//
// these are claims that are added by using the AddClaim, AddClaims methods or passed in the constructor.
[NonSerialized]
List<Claim> m_instanceClaims = new List<Claim>();
// These are claims that are external to the identity. .Net runtime attaches roles owned by principals GenericPrincpal and RolePrincipal here.
// They are not serialized OR remembered when cloned. Access through public method: ClaimProviders.
[NonSerialized]
Collection<IEnumerable<Claim>> m_externalClaims = new Collection<IEnumerable<Claim>>();
[NonSerialized]
string m_nameType = DefaultNameClaimType;
[NonSerialized]
string m_roleType = DefaultRoleClaimType;
[OptionalField(VersionAdded=2)]
string m_version = "1.0";
[OptionalField(VersionAdded = 2)]
ClaimsIdentity m_actor;
[OptionalField(VersionAdded = 2)]
string m_authenticationType;
[OptionalField(VersionAdded = 2)]
object m_bootstrapContext;
[OptionalField(VersionAdded = 2)]
string m_label;
[OptionalField(VersionAdded = 2)]
string m_serializedNameType;
[OptionalField(VersionAdded = 2)]
string m_serializedRoleType;
[OptionalField(VersionAdded = 2)]
string m_serializedClaims;
#region ClaimsIdentity Constructors
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> with an empty claims collection.
/// </summary>
/// <remarks>
/// <see cref="Identity.AuthenticationType"/> is set to null.
/// </remarks>
public ClaimsIdentity()
: this((Claim[])null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using the name and authentication type from
/// an <see cref="IIdentity"/> instance.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> to draw the name and authentication type from.</param>
/// <exception cref="ArgumentNullException"> if <paramref name="identity"/> is null.</exception>
public ClaimsIdentity(IIdentity identity)
: this(identity, (IEnumerable<Claim>)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> using an enumerated collection of
/// <see cref="Claim"/> objects.
/// </summary>
/// <param name="claims">
/// The collection of <see cref="Claim"/> objects to populate <see cref="Identity.Claims"/> with.
/// </param>
/// <remarks>
/// <see cref="Identity.AuthenticationType"/> is set to null.
/// </remarks>
public ClaimsIdentity(IEnumerable<Claim> claims)
: this((IIdentity) null, claims, null, null, null)
{
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> with an empty <see cref="Claim"/> collection
/// and the specified authentication type.
/// </summary>
/// <param name="authenticationType">The type of authentication used.</param>
public ClaimsIdentity(string authenticationType)
: this((IIdentity) null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> using an enumerated collection of
/// <see cref="Claim"/> objects.
/// </summary>
/// <param name="claims">
/// The collection of <see cref="Claim"/> objects to populate <see cref="Identity.Claims"/> with.
/// </param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <remarks>
/// <see cref="Identity.AuthenticationType"/> is set to null.
/// </remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)
: this((IIdentity)null, claims, authenticationType, null, null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using the name and authentication type from
/// an <see cref="IIdentity"/> instance.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> to draw the name and authentication type from.</param>
/// <exception cref="ArgumentNullException"> if <paramref name="identity"/> is null.</exception>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims)
: this(identity, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> with an empty <see cref="Claim"/> collection,
/// the specified authentication type, name claim type, and role claim type.
/// </summary>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The claim type to use for <see cref="Identity.Name"/>.</param>
/// <param name="roleType">The claim type to use for IClaimsPrincipal.IsInRole(string).</param>
public ClaimsIdentity(string authenticationType, string nameType, string roleType )
: this((IIdentity) null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using an enumeration of type
/// <see cref="Claim"/>, authentication type, name claim type, role claim type, and bootstrapContext.
/// </summary>
/// <param name="claims">An enumeration of type <see cref="Claim"/> to initialize this identity</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The claim type to identify NameClaims.</param>
/// <param name="roleType">The claim type to identify RoleClaims.</param>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this((IIdentity)null, claims, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using an enumeration of type
/// <see cref="Claim"/>, authentication type, name claim type, role claim type, and bootstrapContext.
/// </summary>
/// <param name="identity">The initial identity to base this identity from.</param>
/// <param name="claims">An enumeration of type <see cref="Claim"/> to initialize this identity.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The claim type to identify NameClaims.</param>
/// <param name="roleType">The claim type to identify RoleClaims.</param>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this(identity, claims, authenticationType, nameType, roleType, true)
{
}
/// <summary>
/// This constructor was added so that the WindowsIdentity could control if the authenticationType should be checked. For WindowsIdentities this
/// leads to a priviledged call and will fail where the caller has low priviledge.
/// </summary>
/// <param name="identity">The initial identity to base this identity from.</param>
/// <param name="claims">An enumeration of type <see cref="Claim"/> to initialize this identity.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The claim type to identify NameClaims.</param>
/// <param name="roleType">The claim type to identify RoleClaims.</param>
/// <param name="checkAuthType">This boolean flag controls if we blindly set the authenticationType, since call WindowsIdentity.AuthenticationType is a priviledged call.</param>
internal ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType, bool checkAuthType)
{
bool nameTypeSet = false;
bool roleTypeSet = false;
// move the authtype, nameType and roleType over from the identity ONLY if they weren't specifically set.
if(checkAuthType && null != identity && string.IsNullOrEmpty(authenticationType))
{
// can safely ignore UnauthorizedAccessException from WindowsIdentity,
// LSA didn't allow the call and WindowsIdentity throws if property is never accessed, no reason to fail.
if (identity is WindowsIdentity)
{
try
{
m_authenticationType = identity.AuthenticationType;
}
catch (UnauthorizedAccessException)
{
m_authenticationType = null;
}
}
else
{
m_authenticationType = identity.AuthenticationType;
}
}
else
{
m_authenticationType = authenticationType;
}
if(!string.IsNullOrEmpty(nameType))
{
m_nameType = nameType;
nameTypeSet = true;
}
if(!string.IsNullOrEmpty(roleType))
{
m_roleType = roleType;
roleTypeSet = true;
}
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
if (claimsIdentity != null)
{
m_label = claimsIdentity.m_label;
// give preference to parameters
if (!nameTypeSet)
{
m_nameType = claimsIdentity.m_nameType;
}
if (!roleTypeSet)
{
m_roleType = claimsIdentity.m_roleType;
}
m_bootstrapContext = claimsIdentity.m_bootstrapContext;
if (claimsIdentity.Actor != null)
{
//
// Check if the Actor is circular before copying. That check is done while setting
// the Actor property and so not really needed here. But checking just for sanity sake
//
if(!IsCircular(claimsIdentity.Actor))
{
if (!AppContextSwitches.SetActorAsReferenceWhenCopyingClaimsIdentity)
{
m_actor = claimsIdentity.Actor.Clone();
}
else
{
m_actor = claimsIdentity.Actor;
}
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperationException_ActorGraphCircular"));
}
}
// We can only copy over the claims we own, it is up to the derived
// to copy over claims they own.
// BUT we need to special case WindowsIdentity as it keeps its own claims.
// In the case where we are not a windowsIdentity and the claimsIdentity is
// we need to copy the claims
if ((claimsIdentity is WindowsIdentity) && (!(this is WindowsIdentity)))
SafeAddClaims(claimsIdentity.Claims);
else
SafeAddClaims(claimsIdentity.m_instanceClaims);
if (claimsIdentity.m_userSerializationData != null)
{
m_userSerializationData = claimsIdentity.m_userSerializationData.Clone() as byte[];
}
}
else
{
if (identity != null && !string.IsNullOrEmpty(identity.Name))
{
SafeAddClaim(new Claim(m_nameType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this));
}
}
if (claims != null)
{
SafeAddClaims(claims);
}
}
/// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>.
/// Normally the reader is constructed from the bytes returned from <see cref="WriteTo"/>
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsIdentity(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
Initialize(reader);
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected ClaimsIdentity(ClaimsIdentity other)
{
if (other == null)
{
throw new ArgumentNullException("other");
}
if (other.m_actor != null)
{
m_actor = other.m_actor.Clone();
}
m_authenticationType = other.m_authenticationType;
m_bootstrapContext = other.m_bootstrapContext;
m_label = other.m_label;
m_nameType = other.m_nameType;
m_roleType = other.m_roleType;
if (other.m_userSerializationData != null)
{
m_userSerializationData = other.m_userSerializationData.Clone() as byte[];
}
SafeAddClaims(other.m_instanceClaims);
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> from a serialized stream created via
/// <see cref="ISerializable"/>.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> to read from.
/// </param>
/// <param name="context">The <see cref="StreamingContext"/> for serialization. Can be null.</param>
/// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception>
[SecurityCritical]
protected ClaimsIdentity(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException("info");
}
Deserialize(info, context, true);
}
/// <summary>
/// Initializes an instance of <see cref="Identity"/> from a serialized stream created via
/// <see cref="ISerializable"/>.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> to read from.
/// </param>
/// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception>
[SecurityCritical]
protected ClaimsIdentity(SerializationInfo info)
{
if (null == info)
{
throw new ArgumentNullException("info");
}
StreamingContext sc = new StreamingContext();
Deserialize(info, sc, false);
}
#endregion
/// <summary>
/// Gets the authentication type.
/// </summary>
public virtual string AuthenticationType
{
get { return m_authenticationType; }
}
/// <summary>
/// Gets a value that indicates whether the user has been authenticated.
/// </summary>
public virtual bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(m_authenticationType); }
}
/// <summary>
/// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights.
/// </summary>
public ClaimsIdentity Actor
{
get { return m_actor; }
set
{
if(value != null)
{
if(IsCircular(value))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperationException_ActorGraphCircular"));
}
}
m_actor = value;
}
}
/// <summary>
/// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>.
/// </summary>
public object BootstrapContext
{
get { return m_bootstrapContext; }
[SecurityCritical]
set { m_bootstrapContext = value; }
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>May contain nulls.</remarks>
public virtual IEnumerable<Claim> Claims
{
get
{
for (int i = 0; i < m_instanceClaims.Count; i++)
{
yield return m_instanceClaims[i];
}
if (m_externalClaims != null)
{
for (int j = 0; j < m_externalClaims.Count; j++)
{
if (m_externalClaims[j] != null)
{
foreach (Claim claim in m_externalClaims[j])
{
yield return claim;
}
}
}
}
}
}
/// <summary>
/// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.</param>
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return m_userSerializationData;
}
}
/// <summary>
/// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
/// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to Claims.
/// It is recommended the creator of the claims ensures the subject of the claims reflects this <see cref="ClaimsIdentity"/>.
/// </summary>
internal Collection<IEnumerable<Claim>> ExternalClaims
{
[FriendAccessAllowed]
get { return m_externalClaims; }
}
/// <summary>
/// Gets or sets the label for this <see cref="Identity"/>
/// </summary>
public string Label
{
get { return m_label; }
set { m_label = value; }
}
/// <summary>
/// Gets the value of the first claim that has a type of NameClaimType. If no claim is found, null is returned.
/// </summary>
public virtual string Name
{
// just an accessor for getting the name claim
get
{
Claim claim = FindFirst(m_nameType);
if (claim != null)
{
return claim.Value;
}
return null;
}
}
/// <summary>
/// Gets the claim type used to distinguish claims that refer to the name.
/// </summary>
public string NameClaimType
{
get { return m_nameType; }
}
/// <summary>
/// Gets the claim type used to distinguish claims that refer to Roles.
/// </summary>
public string RoleClaimType
{
get { return m_roleType; }
}
/// <summary>
/// Returns a new instance of <see cref="ClaimsIdentity"/> with values copied from this object.
/// </summary>
/// <returns>A new <see cref="Identity"/> object copied from this object</returns>
public virtual ClaimsIdentity Clone()
{
ClaimsIdentity newIdentity = new ClaimsIdentity(m_instanceClaims);
newIdentity.m_authenticationType = this.m_authenticationType;
newIdentity.m_bootstrapContext = this.m_bootstrapContext;
newIdentity.m_label = this.m_label;
newIdentity.m_nameType = this.m_nameType;
newIdentity.m_roleType = this.m_roleType;
if(this.Actor != null)
{
// Check if the Actor is circular before copying. That check is done while setting
// the Actor property and so not really needed here. But checking just for sanity sake
if(!IsCircular(this.Actor))
{
if (!AppContextSwitches.SetActorAsReferenceWhenCopyingClaimsIdentity)
{
newIdentity.Actor = this.Actor.Clone();
}
else
{
newIdentity.Actor = this.Actor;
}
}
else
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperationException_ActorGraphCircular"));
}
}
return newIdentity;
}
/// <summary>
/// Adds a single claim to this ClaimsIdentity. The claim is examined and if the subject != this, then a new claim is
/// created by calling claim.Clone(this). This creates a new claim, with the correct subject.
/// </summary>
/// <param name="claims">Enumeration of claims to add.</param>
/// This is SecurityCritical as we need to control who can add claims to the Identity. Futher down the pipe
/// Authorization decisions will be made based on the claims found in this collection.
[SecurityCritical]
public virtual void AddClaim(Claim claim)
{
if (claim == null)
{
throw new ArgumentNullException("claim");
}
Contract.EndContractBlock();
if(object.ReferenceEquals(claim.Subject, this))
{
m_instanceClaims.Add(claim);
}
else
{
m_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Adds a list of claims to this Claims Identity. Each claim is examined and if the subject != this, then a new claim is
/// created by calling claim.Clone(this). This creates a new claim, with the correct subject.
/// </summary>
/// <param name="claims">Enumeration of claims to add.</param>
/// This is SecurityCritical as we need to control who can add claims to the Identity. Futher down the pipe
/// Authorization decisions will be made based on the claims found in this collection.
[SecurityCritical]
public virtual void AddClaims(IEnumerable<Claim> claims)
{
if (claims == null)
{
throw new ArgumentNullException("claims");
}
Contract.EndContractBlock();
foreach (Claim claim in claims)
{
if (claim == null)
{
continue;
}
AddClaim(claim);
}
}
/// <summary>
/// Attempts to remove a claim from the identity. It is possible that the claim cannot be removed since it is not owned
/// by the identity. This would be the case for role claims that are owned by the Principal.
/// Matches by object reference.
/// <summary/>
[SecurityCritical]
public virtual bool TryRemoveClaim(Claim claim)
{
bool removed = false;
for (int i = 0; i < m_instanceClaims.Count; i++)
{
if (object.ReferenceEquals(m_instanceClaims[i], claim))
{
m_instanceClaims.RemoveAt(i);
removed = true;
break;
}
}
return removed;
}
[SecurityCritical]
public virtual void RemoveClaim(Claim claim)
{
if (!TryRemoveClaim(claim))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ClaimCannotBeRemoved", claim));
}
}
/// <summary>
/// Called from constructor, isolated for easy review
/// This is called from the constructor, this implies that the base class has
/// ownership of holding onto the claims. We can't call AddClaim as that is a virtual and the
/// Derived class may not be constructed yet.
/// </summary>
/// <param name="claims"></param>
[SecuritySafeCritical]
void SafeAddClaims(IEnumerable<Claim> claims)
{
foreach (Claim claim in claims)
{
if (object.ReferenceEquals(claim.Subject, this))
{
m_instanceClaims.Add(claim);
}
else
{
m_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Called from constructor, isolated for easy review.
/// This is called from the constructor, this implies that the base class has
/// ownership of holding onto the claims. We can't call AddClaim as that is a virtual and the
/// Derived class may not be constructed yet.
/// </summary>
/// <param name="claim"></param>
[SecuritySafeCritical]
void SafeAddClaim(Claim claim)
{
if (object.ReferenceEquals(claim.Subject, this))
{
m_instanceClaims.Add(claim);
}
else
{
m_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
List<Claim> claims = new List<Claim>();
foreach (Claim claim in Claims)
{
if (match(claim))
{
claims.Add(claim);
}
}
return claims.AsReadOnly();
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Comparison is made using Ordinal case in-sensitive on type.<</remarks>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
List<Claim> claims = new List<Claim>();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
claims.Add(claim);
}
}
}
return claims.AsReadOnly();
}
/// <summary>
/// Determines if a claim is contained within this ClaimsIdentity.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a claim with type AND value is contained in the claims within this ClaimsIdentity.
/// </summary>
/// <param name="type"> the type of the claim to match.</param>
/// <param name="value"> the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Does not check Issuer or OriginalIssuer. Comparison is made using Ordinal, case sensitive on value, case in-sensitive on type.</remarks>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (claim != null
&& string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)
&& string.Equals(claim.Value, value, StringComparison.Ordinal))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <param name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Comparison is made using Ordinal, case in-sensitive.</remarks>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException("match");
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return claim;
}
}
return null;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Comparison is made using Ordinal, case in-sensitive.</remarks>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
}
return null;
}
[OnSerializing()]
[SecurityCritical]
private void OnSerializingMethod(StreamingContext context)
{
if (this is ISerializable)
return;
m_serializedClaims = SerializeClaims();
m_serializedNameType = m_nameType;
m_serializedRoleType = m_roleType;
}
[OnDeserialized()]
[SecurityCritical]
private void OnDeserializedMethod(StreamingContext context)
{
if (this is ISerializable)
return;
if (!String.IsNullOrEmpty(m_serializedClaims))
{
DeserializeClaims(m_serializedClaims);
m_serializedClaims = null;
}
m_nameType = string.IsNullOrEmpty(m_serializedNameType) ? DefaultNameClaimType : m_serializedNameType;
m_roleType = string.IsNullOrEmpty(m_serializedRoleType) ? DefaultRoleClaimType : m_serializedRoleType;
}
[OnDeserializing()]
private void OnDeserializingMethod(StreamingContext context)
{
if (this is ISerializable)
return;
m_instanceClaims = new List<Claim>();
m_externalClaims = new Collection<IEnumerable<Claim>>();
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity
/// </summary>
/// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param>
/// <param name="context">Context for serialization. Can be null.</param>
/// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception>
[SecurityCritical]
[SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
BinaryFormatter formatter = new BinaryFormatter();
info.AddValue(VersionKey, m_version);
if (!string.IsNullOrEmpty(m_authenticationType))
{
info.AddValue(AuthenticationTypeKey, m_authenticationType);
}
info.AddValue(NameClaimTypeKey, m_nameType);
info.AddValue(RoleClaimTypeKey, m_roleType);
if (!string.IsNullOrEmpty(m_label))
{
info.AddValue(LabelKey, m_label);
}