DigestStore.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. namespace Best.HTTP.Request.Authentication
  5. {
  6. /// <summary>
  7. /// Stores and manages already received digest infos.
  8. /// </summary>
  9. public static class DigestStore
  10. {
  11. private static ConcurrentDictionary<string, Digest> Digests = new ConcurrentDictionary<string, Digest>();
  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. if (Digests.TryGetValue(uri.Host, out var digest))
  19. if (!digest.IsUriProtected(uri))
  20. return null;
  21. return digest;
  22. }
  23. /// <summary>
  24. /// It will retrieve or create a new Digest for the given Uri.
  25. /// </summary>
  26. /// <param name="uri"></param>
  27. /// <returns></returns>
  28. public static Digest GetOrCreate(Uri uri) => Digests.GetOrAdd(uri.Host, new Digest(uri));
  29. public static void Remove(Uri uri) => Digests.TryRemove(uri.Host, out var _);
  30. public static void Clear() => Digests.Clear();
  31. public static string FindBest(List<string> authHeaders)
  32. {
  33. if (authHeaders == null || authHeaders.Count == 0)
  34. return string.Empty;
  35. List<string> headers = new List<string>(authHeaders.Count);
  36. for (int i = 0; i < authHeaders.Count; ++i)
  37. headers.Add(authHeaders[i].ToLowerInvariant());
  38. for (int i = 0; i < SupportedAlgorithms.Length; ++i)
  39. {
  40. int idx = headers.FindIndex((header) => header.StartsWith(SupportedAlgorithms[i]));
  41. if (idx != -1)
  42. return authHeaders[idx];
  43. }
  44. return string.Empty;
  45. }
  46. }
  47. }