1
0

BasicHttpAuthentication.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.Reflection;
  5. using Nini.Config;
  6. using log4net;
  7. namespace OpenSim.Framework.ServiceAuth
  8. {
  9. public class BasicHttpAuthentication : IServiceAuth
  10. {
  11. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  12. private string m_Username, m_Password;
  13. private string m_CredentialsB64;
  14. private string remove_me;
  15. public string Credentials
  16. {
  17. get { return m_CredentialsB64; }
  18. }
  19. public BasicHttpAuthentication(IConfigSource config, string section)
  20. {
  21. remove_me = section;
  22. m_Username = Util.GetConfigVarFromSections<string>(config, "HttpAuthUsername", new string[] { "Network", section }, string.Empty);
  23. m_Password = Util.GetConfigVarFromSections<string>(config, "HttpAuthPassword", new string[] { "Network", section }, string.Empty);
  24. string str = m_Username + ":" + m_Password;
  25. byte[] encData_byte = Util.UTF8.GetBytes(str);
  26. m_CredentialsB64 = Convert.ToBase64String(encData_byte);
  27. m_log.DebugFormat("[HTTP BASIC AUTH]: {0} {1} [{2}]", m_Username, m_Password, section);
  28. }
  29. public void AddAuthorization(NameValueCollection headers)
  30. {
  31. //m_log.DebugFormat("[HTTP BASIC AUTH]: Adding authorization for {0}", remove_me);
  32. headers["Authorization"] = "Basic " + m_CredentialsB64;
  33. }
  34. public bool Authenticate(string data)
  35. {
  36. string recovered = Util.Base64ToString(data);
  37. if (!String.IsNullOrEmpty(recovered))
  38. {
  39. string[] parts = recovered.Split(new char[] { ':' });
  40. if (parts.Length >= 2)
  41. {
  42. return m_Username.Equals(parts[0]) && m_Password.Equals(parts[1]);
  43. }
  44. }
  45. return false;
  46. }
  47. public bool Authenticate(NameValueCollection requestHeaders, AddHeaderDelegate d)
  48. {
  49. //m_log.DebugFormat("[HTTP BASIC AUTH]: Authenticate in {0}", remove_me);
  50. if (requestHeaders != null)
  51. {
  52. string value = requestHeaders.Get("Authorization");
  53. if (value != null)
  54. {
  55. value = value.Trim();
  56. if (value.StartsWith("Basic "))
  57. {
  58. value = value.Replace("Basic ", string.Empty);
  59. if (Authenticate(value))
  60. return true;
  61. }
  62. }
  63. }
  64. d("WWW-Authenticate", "Basic realm = \"Asset Server\"");
  65. return false;
  66. }
  67. }
  68. }