mscorlib(4.0.0.0) API with additions
ClaimsPrincipal.cs
3 using System.IO;
9 using System.Threading;
10 
11 namespace System.Security.Claims
12 {
14  [Serializable]
15  [ComVisible(true)]
16  public class ClaimsPrincipal : IPrincipal
17  {
18  private enum SerializationMask
19  {
20  None,
21  HasIdentities,
22  UserData
23  }
24 
25  [NonSerialized]
26  private byte[] m_userSerializationData;
27 
28  [NonSerialized]
29  private const string PreFix = "System.Security.ClaimsPrincipal.";
30 
31  [NonSerialized]
32  private const string IdentitiesKey = "System.Security.ClaimsPrincipal.Identities";
33 
34  [NonSerialized]
35  private const string VersionKey = "System.Security.ClaimsPrincipal.Version";
36 
37  [OptionalField(VersionAdded = 2)]
38  private string m_version = "1.0";
39 
40  [OptionalField(VersionAdded = 2)]
41  private string m_serializedClaimsIdentities;
42 
43  [NonSerialized]
44  private List<ClaimsIdentity> m_identities = new List<ClaimsIdentity>();
45 
46  [NonSerialized]
47  private static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> s_identitySelector = SelectPrimaryIdentity;
48 
49  [NonSerialized]
50  private static Func<ClaimsPrincipal> s_principalSelector = ClaimsPrincipalSelector;
51 
54  public static Func<IEnumerable<ClaimsIdentity>, ClaimsIdentity> PrimaryIdentitySelector
55  {
56  get
57  {
58  return s_identitySelector;
59  }
60  [SecurityCritical]
61  set
62  {
63  s_identitySelector = value;
64  }
65  }
66 
69  public static Func<ClaimsPrincipal> ClaimsPrincipalSelector
70  {
71  get
72  {
73  return s_principalSelector;
74  }
75  [SecurityCritical]
76  set
77  {
78  s_principalSelector = value;
79  }
80  }
81 
83  protected virtual byte[] CustomSerializationData => m_userSerializationData;
84 
87  public virtual IEnumerable<Claim> Claims
88  {
89  get
90  {
91  foreach (ClaimsIdentity identity in Identities)
92  {
93  foreach (Claim claim in identity.Claims)
94  {
95  yield return claim;
96  }
97  }
98  }
99  }
100 
103  public static ClaimsPrincipal Current
104  {
105  get
106  {
107  if (s_principalSelector != null)
108  {
109  return s_principalSelector();
110  }
111  return SelectClaimsPrincipal();
112  }
113  }
114 
117  public virtual IEnumerable<ClaimsIdentity> Identities => m_identities.AsReadOnly();
118 
121  public virtual IIdentity Identity
122  {
123  get
124  {
125  if (s_identitySelector != null)
126  {
127  return s_identitySelector(m_identities);
128  }
129  return SelectPrimaryIdentity(m_identities);
130  }
131  }
132 
133  private static ClaimsIdentity SelectPrimaryIdentity(IEnumerable<ClaimsIdentity> identities)
134  {
135  if (identities == null)
136  {
137  throw new ArgumentNullException("identities");
138  }
139  ClaimsIdentity claimsIdentity = null;
140  foreach (ClaimsIdentity identity in identities)
141  {
142  if (identity is WindowsIdentity)
143  {
144  return identity;
145  }
146  if (claimsIdentity == null)
147  {
148  claimsIdentity = identity;
149  }
150  }
151  return claimsIdentity;
152  }
153 
154  private static ClaimsPrincipal SelectClaimsPrincipal()
155  {
157  if (claimsPrincipal != null)
158  {
159  return claimsPrincipal;
160  }
162  }
163 
166  {
167  }
168 
174  {
175  if (identities == null)
176  {
177  throw new ArgumentNullException("identities");
178  }
179  m_identities.AddRange(identities);
180  }
181 
186  public ClaimsPrincipal(IIdentity identity)
187  {
188  if (identity == null)
189  {
190  throw new ArgumentNullException("identity");
191  }
192  ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
193  if (claimsIdentity != null)
194  {
195  m_identities.Add(claimsIdentity);
196  }
197  else
198  {
199  m_identities.Add(new ClaimsIdentity(identity));
200  }
201  }
202 
207  public ClaimsPrincipal(IPrincipal principal)
208  {
209  if (principal == null)
210  {
211  throw new ArgumentNullException("principal");
212  }
213  ClaimsPrincipal claimsPrincipal = principal as ClaimsPrincipal;
214  if (claimsPrincipal == null)
215  {
216  m_identities.Add(new ClaimsIdentity(principal.Identity));
217  }
218  else if (claimsPrincipal.Identities != null)
219  {
220  m_identities.AddRange(claimsPrincipal.Identities);
221  }
222  }
223 
227  {
228  if (reader == null)
229  {
230  throw new ArgumentNullException("reader");
231  }
232  Initialize(reader);
233  }
234 
240  [SecurityCritical]
242  {
243  if (info == null)
244  {
245  throw new ArgumentNullException("info");
246  }
247  Deserialize(info, context);
248  }
249 
252  public virtual ClaimsPrincipal Clone()
253  {
254  return new ClaimsPrincipal(this);
255  }
256 
261  {
262  if (reader == null)
263  {
264  throw new ArgumentNullException("reader");
265  }
266  return new ClaimsIdentity(reader);
267  }
268 
269  [OnSerializing]
270  [SecurityCritical]
271  private void OnSerializingMethod(StreamingContext context)
272  {
273  if (!(this is ISerializable))
274  {
275  m_serializedClaimsIdentities = SerializeIdentities();
276  }
277  }
278 
279  [OnDeserialized]
280  [SecurityCritical]
281  private void OnDeserializedMethod(StreamingContext context)
282  {
283  if (!(this is ISerializable))
284  {
285  DeserializeIdentities(m_serializedClaimsIdentities);
286  m_serializedClaimsIdentities = null;
287  }
288  }
289 
295  [SecurityCritical]
296  [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
297  protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
298  {
299  if (info == null)
300  {
301  throw new ArgumentNullException("info");
302  }
303  info.AddValue("System.Security.ClaimsPrincipal.Identities", SerializeIdentities());
304  info.AddValue("System.Security.ClaimsPrincipal.Version", m_version);
305  }
306 
307  [SecurityCritical]
308  [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
309  private void Deserialize(SerializationInfo info, StreamingContext context)
310  {
311  if (info == null)
312  {
313  throw new ArgumentNullException("info");
314  }
315  SerializationInfoEnumerator enumerator = info.GetEnumerator();
316  while (enumerator.MoveNext())
317  {
318  string name = enumerator.Name;
319  if (!(name == "System.Security.ClaimsPrincipal.Identities"))
320  {
321  if (name == "System.Security.ClaimsPrincipal.Version")
322  {
323  m_version = info.GetString("System.Security.ClaimsPrincipal.Version");
324  }
325  }
326  else
327  {
328  DeserializeIdentities(info.GetString("System.Security.ClaimsPrincipal.Identities"));
329  }
330  }
331  }
332 
333  [SecurityCritical]
334  private void DeserializeIdentities(string identities)
335  {
336  m_identities = new List<ClaimsIdentity>();
337  if (!string.IsNullOrEmpty(identities))
338  {
339  List<string> list = null;
340  BinaryFormatter binaryFormatter = new BinaryFormatter();
341  using (MemoryStream serializationStream = new MemoryStream(Convert.FromBase64String(identities)))
342  {
343  list = (List<string>)binaryFormatter.Deserialize(serializationStream, null, fCheck: false);
344  int num = 0;
345  while (true)
346  {
347  if (num >= list.Count)
348  {
349  return;
350  }
351  ClaimsIdentity claimsIdentity = null;
352  using (MemoryStream serializationStream2 = new MemoryStream(Convert.FromBase64String(list[num + 1])))
353  {
354  claimsIdentity = (ClaimsIdentity)binaryFormatter.Deserialize(serializationStream2, null, fCheck: false);
355  }
356  if (!string.IsNullOrEmpty(list[num]))
357  {
358  if (!long.TryParse(list[num], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out long result))
359  {
360  break;
361  }
362  claimsIdentity = new WindowsIdentity(claimsIdentity, new IntPtr(result));
363  }
364  m_identities.Add(claimsIdentity);
365  num += 2;
366  }
367  throw new SerializationException(Environment.GetResourceString("Serialization_CorruptedStream"));
368  }
369  }
370  }
371 
372  [SecurityCritical]
373  private string SerializeIdentities()
374  {
375  List<string> list = new List<string>();
376  BinaryFormatter binaryFormatter = new BinaryFormatter();
377  foreach (ClaimsIdentity identity in m_identities)
378  {
379  if (identity.GetType() == typeof(WindowsIdentity))
380  {
381  WindowsIdentity windowsIdentity = identity as WindowsIdentity;
382  list.Add(windowsIdentity.GetTokenInternal().ToInt64().ToString(NumberFormatInfo.InvariantInfo));
383  using (MemoryStream memoryStream = new MemoryStream())
384  {
385  binaryFormatter.Serialize(memoryStream, windowsIdentity.CloneAsBase(), null, fCheck: false);
386  list.Add(Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length));
387  }
388  }
389  else
390  {
391  using (MemoryStream memoryStream2 = new MemoryStream())
392  {
393  list.Add("");
394  binaryFormatter.Serialize(memoryStream2, identity, null, fCheck: false);
395  list.Add(Convert.ToBase64String(memoryStream2.GetBuffer(), 0, (int)memoryStream2.Length));
396  }
397  }
398  }
399  using (MemoryStream memoryStream3 = new MemoryStream())
400  {
401  binaryFormatter.Serialize(memoryStream3, list, null, fCheck: false);
402  return Convert.ToBase64String(memoryStream3.GetBuffer(), 0, (int)memoryStream3.Length);
403  }
404  }
405 
410  [SecurityCritical]
411  public virtual void AddIdentity(ClaimsIdentity identity)
412  {
413  if (identity == null)
414  {
415  throw new ArgumentNullException("identity");
416  }
417  m_identities.Add(identity);
418  }
419 
424  [SecurityCritical]
425  public virtual void AddIdentities(IEnumerable<ClaimsIdentity> identities)
426  {
427  if (identities == null)
428  {
429  throw new ArgumentNullException("identities");
430  }
431  m_identities.AddRange(identities);
432  }
433 
439  public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
440  {
441  if (match == null)
442  {
443  throw new ArgumentNullException("match");
444  }
445  List<Claim> list = new List<Claim>();
446  foreach (ClaimsIdentity identity in Identities)
447  {
448  if (identity != null)
449  {
450  foreach (Claim item in identity.FindAll(match))
451  {
452  list.Add(item);
453  }
454  }
455  }
456  return list.AsReadOnly();
457  }
458 
464  public virtual IEnumerable<Claim> FindAll(string type)
465  {
466  if (type == null)
467  {
468  throw new ArgumentNullException("type");
469  }
470  List<Claim> list = new List<Claim>();
471  foreach (ClaimsIdentity identity in Identities)
472  {
473  if (identity != null)
474  {
475  foreach (Claim item in identity.FindAll(type))
476  {
477  list.Add(item);
478  }
479  }
480  }
481  return list.AsReadOnly();
482  }
483 
489  public virtual Claim FindFirst(Predicate<Claim> match)
490  {
491  if (match == null)
492  {
493  throw new ArgumentNullException("match");
494  }
495  Claim claim = null;
496  foreach (ClaimsIdentity identity in Identities)
497  {
498  if (identity != null)
499  {
500  claim = identity.FindFirst(match);
501  if (claim != null)
502  {
503  return claim;
504  }
505  }
506  }
507  return claim;
508  }
509 
515  public virtual Claim FindFirst(string type)
516  {
517  if (type == null)
518  {
519  throw new ArgumentNullException("type");
520  }
521  Claim claim = null;
522  for (int i = 0; i < m_identities.Count; i++)
523  {
524  if (m_identities[i] != null)
525  {
526  claim = m_identities[i].FindFirst(type);
527  if (claim != null)
528  {
529  return claim;
530  }
531  }
532  }
533  return claim;
534  }
535 
542  public virtual bool HasClaim(Predicate<Claim> match)
543  {
544  if (match == null)
545  {
546  throw new ArgumentNullException("match");
547  }
548  for (int i = 0; i < m_identities.Count; i++)
549  {
550  if (m_identities[i] != null && m_identities[i].HasClaim(match))
551  {
552  return true;
553  }
554  }
555  return false;
556  }
557 
566  public virtual bool HasClaim(string type, string value)
567  {
568  if (type == null)
569  {
570  throw new ArgumentNullException("type");
571  }
572  if (value == null)
573  {
574  throw new ArgumentNullException("value");
575  }
576  for (int i = 0; i < m_identities.Count; i++)
577  {
578  if (m_identities[i] != null && m_identities[i].HasClaim(type, value))
579  {
580  return true;
581  }
582  }
583  return false;
584  }
585 
590  public virtual bool IsInRole(string role)
591  {
592  for (int i = 0; i < m_identities.Count; i++)
593  {
594  if (m_identities[i] != null && m_identities[i].HasClaim(m_identities[i].RoleClaimType, role))
595  {
596  return true;
597  }
598  }
599  return false;
600  }
601 
602  private void Initialize(BinaryReader reader)
603  {
604  if (reader == null)
605  {
606  throw new ArgumentNullException("reader");
607  }
608  SerializationMask serializationMask = (SerializationMask)reader.ReadInt32();
609  int num = reader.ReadInt32();
610  int num2 = 0;
611  if ((serializationMask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
612  {
613  num2++;
614  int num3 = reader.ReadInt32();
615  for (int i = 0; i < num3; i++)
616  {
617  m_identities.Add(CreateClaimsIdentity(reader));
618  }
619  }
620  if ((serializationMask & SerializationMask.UserData) == SerializationMask.UserData)
621  {
622  int count = reader.ReadInt32();
623  m_userSerializationData = reader.ReadBytes(count);
624  num2++;
625  }
626  for (int j = num2; j < num; j++)
627  {
628  reader.ReadString();
629  }
630  }
631 
634  public virtual void WriteTo(BinaryWriter writer)
635  {
636  WriteTo(writer, null);
637  }
638 
642  protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
643  {
644  if (writer == null)
645  {
646  throw new ArgumentNullException("writer");
647  }
648  int num = 0;
649  SerializationMask serializationMask = SerializationMask.None;
650  if (m_identities.Count > 0)
651  {
652  serializationMask |= SerializationMask.HasIdentities;
653  num++;
654  }
655  if (userData != null && userData.Length != 0)
656  {
657  num++;
658  serializationMask |= SerializationMask.UserData;
659  }
660  writer.Write((int)serializationMask);
661  writer.Write(num);
662  if ((serializationMask & SerializationMask.HasIdentities) == SerializationMask.HasIdentities)
663  {
664  writer.Write(m_identities.Count);
665  foreach (ClaimsIdentity identity in m_identities)
666  {
667  identity.WriteTo(writer);
668  }
669  }
670  if ((serializationMask & SerializationMask.UserData) == SerializationMask.UserData)
671  {
672  writer.Write(userData.Length);
673  writer.Write(userData);
674  }
675  writer.Flush();
676  }
677  }
678 }
static IPrincipal CurrentPrincipal
Gets or sets the thread's current principal (for role-based security).
Definition: Thread.cs:297
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
override long Length
Gets the length of the stream in bytes.
virtual void WriteTo(BinaryWriter writer, byte[] userData)
static Func< ClaimsPrincipal > ClaimsPrincipalSelector
Gets and sets the delegate used to select the claims principal returned by the P:System....
virtual int ReadInt32()
Reads a 4-byte signed integer from the current stream and advances the current position of the stream...
virtual void AddIdentities(IEnumerable< ClaimsIdentity > identities)
Adds the specified claims identities to this claims principal.
virtual void Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlyin...
Defines the basic functionality of a principal object.
Definition: IPrincipal.cs:8
ReadOnlyCollection< T > AsReadOnly()
Returns a read-only T:System.Collections.ObjectModel.ReadOnlyCollection`1 wrapper for the current col...
Definition: List.cs:553
void Serialize(Stream serializationStream, object graph)
Serializes the object, or graph of objects with the specified top (root), to the given stream.
Definition: __Canon.cs:3
static Func< IEnumerable< ClaimsIdentity >, ClaimsIdentity > PrimaryIdentitySelector
Gets and sets the delegate used to select the claims identity returned by the P:System....
ClaimsPrincipal(SerializationInfo info, StreamingContext context)
Initializes a new instance of the T:System.Security.Claims.ClaimsPrincipal class from a serialized st...
unsafe long ToInt64()
Converts the value of this instance to a 64-bit signed integer.
Definition: IntPtr.cs:147
virtual IEnumerable< Claim > FindAll(string type)
Retrieves all or the claims that have the specified claim type.
Describes the source and destination of a given serialized stream, and provides an additional caller-...
object Deserialize(Stream serializationStream)
Deserializes the specified stream into an object graph.
virtual IIdentity Identity
Gets the primary claims identity associated with this claims principal.
virtual IEnumerable< Claim > FindAll(Predicate< Claim > match)
Retrieves all of the claims that are matched by the specified predicate.
virtual bool HasClaim(string type, string value)
Determines whether any of the claims identities associated with this claims principal contains a clai...
Serializes and deserializes an object, or an entire graph of connected objects, in binary format.
virtual ClaimsIdentity CreateClaimsIdentity(BinaryReader reader)
Creates a new claims identity.
NumberStyles
Determines the styles permitted in numeric string arguments that are passed to the Parse and TryParse...
Definition: NumberStyles.cs:10
virtual byte [] GetBuffer()
Returns the array of unsigned bytes from which this stream was created.
virtual bool HasClaim(Predicate< Claim > match)
Determines whether any of the claims identities associated with this claims principal contains a clai...
void Add(T item)
Adds an object to the end of the T:System.Collections.Generic.List`1.
Definition: List.cs:510
SecurityAction
Specifies the security actions that can be performed using declarative security.
virtual bool IsInRole(string role)
Returns a value that indicates whether the entity (user) represented by this claims principal is in t...
virtual Claim FindFirst(Predicate< Claim > match)
Retrieves the first claim that is matched by the specified predicate.
IIdentity Identity
Gets the identity of the current principal.
Definition: IPrincipal.cs:14
virtual void GetObjectData(SerializationInfo info, StreamingContext context)
Populates the T:System.Runtime.Serialization.SerializationInfo with data needed to serialize the curr...
Creates a stream whose backing store is memory.To browse the .NET Framework source code for this type...
Definition: MemoryStream.cs:13
An T:System.Security.Principal.IPrincipal implementation that supports multiple claims-based identiti...
virtual IEnumerable< Claim > Claims
Gets a collection that contains all of the claims from all of the claims identities associated with t...
A cast or conversion operation, such as (SampleType)obj in C::or CType(obj, SampleType) in Visual Bas...
ClaimsPrincipal()
Initializes a new instance of the T:System.Security.Claims.ClaimsPrincipal class.
virtual byte [] ReadBytes(int count)
Reads the specified number of bytes from the current stream into a byte array and advances the curren...
Reads primitive data types as binary values in a specific encoding.
Definition: BinaryReader.cs:10
virtual void WriteTo(BinaryWriter writer)
Represents a claim.
Definition: Claim.cs:10
virtual ClaimsPrincipal Clone()
Returns a copy of this instance.
Represents a claims-based identity.
The exception thrown when an error occurs during serialization or deserialization.
virtual void Write(bool value)
Writes a one-byte Boolean value to the current stream, with 0 representing false and 1 representing t...
void AddRange(IEnumerable< T > collection)
Adds the elements of the specified collection to the end of the T:System.Collections....
Definition: List.cs:545
Stores all the data needed to serialize or deserialize an object. This class cannot be inherited.
virtual Claim FindFirst(string type)
Retrieves the first claim with the specified claim type.
ClaimsPrincipal(IEnumerable< ClaimsIdentity > identities)
Initializes a new instance of the T:System.Security.Claims.ClaimsPrincipal class using the specified ...
virtual void WriteTo(BinaryWriter writer)
Allows an object to control its own serialization and deserialization.
Definition: ISerializable.cs:8
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search...
Definition: List.cs:14
Specifies that the class can be serialized.
string Name
Gets the name for the item currently being examined.
Defines the basic functionality of an identity object.
Definition: IIdentity.cs:8
static ClaimsPrincipal Current
Gets the current claims principal.
virtual string ReadString()
Reads a string from the current stream. The string is prefixed with the length, encoded as an integer...
virtual Claim FindFirst(Predicate< Claim > match)
Retrieves the first claim that is matched by the specified predicate.
virtual IEnumerable< Claim > FindAll(Predicate< Claim > match)
Retrieves all of the claims that are matched by the specified predicate.
virtual void AddIdentity(ClaimsIdentity identity)
Adds the specified claims identity to this claims principal.
Writes primitive types in binary to a stream and supports writing strings in a specific encoding.
Definition: BinaryWriter.cs:12
Provides a formatter-friendly mechanism for parsing the data in T:System.Runtime.Serialization....
virtual IEnumerable< ClaimsIdentity > Identities
Gets a collection that contains all of the claims identities associated with this claims principal.
ClaimsPrincipal(IIdentity identity)
Initializes a new instance of the T:System.Security.Claims.ClaimsPrincipal class from the specified i...
static NumberFormatInfo InvariantInfo
Gets a read-only T:System.Globalization.NumberFormatInfo object that is culture-independent (invarian...
virtual IEnumerable< Claim > Claims
Gets the claims associated with this claims identity.
bool MoveNext()
Updates the enumerator to the next item.
ClaimsPrincipal(IPrincipal principal)
Initializes a new instance of the T:System.Security.Claims.ClaimsPrincipal class from the specified p...
Provides culture-specific information for formatting and parsing numeric values.
Creates and controls a thread, sets its priority, and gets its status.
Definition: Thread.cs:18