DigestStore.cs 2.2 KB

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