DigestStore.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using BestHTTP.PlatformSupport.Threading;
  4. namespace BestHTTP.Authentication
  5. {
  6. /// <summary>
  7. /// Stores and manages already received digest infos.
  8. /// </summary>
  9. public static class DigestStore
  10. {
  11. private static Dictionary<string, Digest> Digests = new Dictionary<string, Digest>();
  12. private static System.Threading.ReaderWriterLockSlim rwLock = new System.Threading.ReaderWriterLockSlim(System.Threading.LockRecursionPolicy.NoRecursion);
  13. /// <summary>
  14. /// Array of algorithms that the plugin supports. It's in the order of priority(first has the highest priority).
  15. /// </summary>
  16. private static string[] SupportedAlgorithms = new string[] { "digest", "basic" };
  17. public static Digest Get(Uri uri)
  18. {
  19. using (new ReadLock(rwLock))
  20. {
  21. Digest digest = null;
  22. if (Digests.TryGetValue(uri.Host, out digest))
  23. if (!digest.IsUriProtected(uri))
  24. return null;
  25. return digest;
  26. }
  27. }
  28. /// <summary>
  29. /// It will retrieve or create a new Digest for the given Uri.
  30. /// </summary>
  31. /// <param name="uri"></param>
  32. /// <returns></returns>
  33. public static Digest GetOrCreate(Uri uri)
  34. {
  35. using (new WriteLock(rwLock))
  36. {
  37. Digest digest = null;
  38. if (!Digests.TryGetValue(uri.Host, out digest))
  39. Digests.Add(uri.Host, digest = new Digest(uri));
  40. return digest;
  41. }
  42. }
  43. public static void Remove(Uri uri)
  44. {
  45. using (new WriteLock(rwLock))
  46. Digests.Remove(uri.Host);
  47. }
  48. public static string FindBest(List<string> authHeaders)
  49. {
  50. if (authHeaders == null || authHeaders.Count == 0)
  51. return string.Empty;
  52. List<string> headers = new List<string>(authHeaders.Count);
  53. for (int i = 0; i < authHeaders.Count; ++i)
  54. headers.Add(authHeaders[i].ToLower());
  55. for (int i = 0; i < SupportedAlgorithms.Length; ++i)
  56. {
  57. int idx = headers.FindIndex((header) => header.StartsWith(SupportedAlgorithms[i]));
  58. if (idx != -1)
  59. return authHeaders[idx];
  60. }
  61. return string.Empty;
  62. }
  63. }
  64. }