FormsAuthentication.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. //
  2. // System.Web.Security.FormsAuthentication
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Web;
  14. using System.Web.Configuration;
  15. using System.Web.Util;
  16. namespace System.Web.Security
  17. {
  18. public sealed class FormsAuthentication
  19. {
  20. static string authConfigPath = "system.web/authentication";
  21. static bool initialized;
  22. static string cookieName;
  23. static string cookiePath;
  24. static int timeout;
  25. static FormsProtectionEnum protection;
  26. public static bool Authenticate (string name, string password)
  27. {
  28. if (name == null || password == null)
  29. return false;
  30. Initialize ();
  31. HttpContext context = HttpContext.Current;
  32. if (context == null)
  33. throw new HttpException ("Context is null!");
  34. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  35. Hashtable users = config.CredentialUsers;
  36. string stored = users [name] as string;
  37. if (stored == null)
  38. return false;
  39. switch (config.PasswordFormat) {
  40. case FormsAuthPasswordFormat.Clear:
  41. /* Do nothing */
  42. break;
  43. case FormsAuthPasswordFormat.MD5:
  44. stored = HashPasswordForStoringInConfigFile (stored, "MD5");
  45. break;
  46. case FormsAuthPasswordFormat.SHA1:
  47. stored = HashPasswordForStoringInConfigFile (stored, "SHA1");
  48. break;
  49. }
  50. return (password == stored);
  51. }
  52. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  53. {
  54. if (encryptedTicket == null || encryptedTicket == String.Empty)
  55. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  56. Initialize ();
  57. byte [] bytes = MachineKeyConfigHandler.GetBytes (encryptedTicket, encryptedTicket.Length);
  58. //TODO: decrypt
  59. string decrypted = WebEncoding.Encoding.GetString (bytes);
  60. FormsAuthenticationTicket ticket = null;
  61. try {
  62. string [] values = decrypted.Split ((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7);
  63. if (values.Length != 8)
  64. throw new Exception (values.Length + " " + encryptedTicket);
  65. ticket = new FormsAuthenticationTicket (Int32.Parse (values [0]),
  66. values [1],
  67. new DateTime (Int64.Parse (values [2])),
  68. new DateTime (Int64.Parse (values [3])),
  69. (values [4] == "1"),
  70. values [5],
  71. values [6]);
  72. } catch (Exception e) {
  73. ticket = null;
  74. }
  75. return ticket;
  76. }
  77. public static string Encrypt (FormsAuthenticationTicket ticket)
  78. {
  79. if (ticket == null)
  80. throw new ArgumentNullException ("ticket");
  81. Initialize ();
  82. StringBuilder allTicket = new StringBuilder ();
  83. allTicket.Append (ticket.Version);
  84. allTicket.Append ('\u0001');
  85. allTicket.Append (ticket.Name);
  86. allTicket.Append ('\u0002');
  87. allTicket.Append (ticket.IssueDate.Ticks);
  88. allTicket.Append ('\u0003');
  89. allTicket.Append (ticket.Expiration.Ticks);
  90. allTicket.Append ('\u0004');
  91. allTicket.Append (ticket.IsPersistent ? '1' : '0');
  92. allTicket.Append ('\u0005');
  93. allTicket.Append (ticket.UserData);
  94. allTicket.Append ('\u0006');
  95. allTicket.Append (ticket.CookiePath);
  96. allTicket.Append ('\u0007');
  97. //if (protection == FormsProtectionEnum.None)
  98. return GetHexString (allTicket.ToString ());
  99. //TODO: encrypt and validate
  100. }
  101. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  102. {
  103. return GetAuthCookie (userName, createPersistentCookie, cookiePath);
  104. }
  105. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  106. {
  107. Initialize ();
  108. if (userName == null)
  109. userName = String.Empty;
  110. if (strCookiePath == null || strCookiePath.Length == 0)
  111. strCookiePath = cookiePath;
  112. DateTime now = DateTime.Now;
  113. DateTime then;
  114. if (createPersistentCookie)
  115. then = now.AddYears (50);
  116. else
  117. then = now.AddMinutes (timeout);
  118. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  119. userName,
  120. now,
  121. then,
  122. createPersistentCookie,
  123. String.Empty,
  124. cookiePath);
  125. if (!createPersistentCookie)
  126. then = DateTime.MinValue;
  127. return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  128. }
  129. [MonoTODO]
  130. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  131. {
  132. throw new NotImplementedException ();
  133. }
  134. static string GetHexString (string str)
  135. {
  136. return GetHexString (WebEncoding.Encoding.GetBytes (str));
  137. }
  138. static string GetHexString (byte [] bytes)
  139. {
  140. StringBuilder result = new StringBuilder (bytes.Length * 2);
  141. foreach (byte b in bytes)
  142. result.AppendFormat ("{0:x2}", (int) b);
  143. return result.ToString ();
  144. }
  145. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  146. {
  147. if (password == null)
  148. throw new ArgumentNullException ("password");
  149. if (passwordFormat == null)
  150. throw new ArgumentNullException ("passwordFormat");
  151. byte [] bytes;
  152. if (String.Compare (passwordFormat, "MD5", true) == 0) {
  153. bytes = MD5.Create ().ComputeHash (WebEncoding.Encoding.GetBytes (password));
  154. } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
  155. bytes = SHA1.Create ().ComputeHash (WebEncoding.Encoding.GetBytes (password));
  156. } else {
  157. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  158. }
  159. return GetHexString (bytes);
  160. }
  161. public static void Initialize ()
  162. {
  163. if (initialized)
  164. return;
  165. lock (typeof (FormsAuthentication)) {
  166. if (initialized)
  167. return;
  168. HttpContext context = HttpContext.Current;
  169. if (context == null)
  170. throw new HttpException ("Context is null!");
  171. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  172. if (authConfig != null) {
  173. cookieName = authConfig.CookieName;
  174. timeout = authConfig.Timeout;
  175. cookiePath = authConfig.CookiePath;
  176. protection = authConfig.Protection;
  177. } else {
  178. cookieName = ".MONOAUTH";
  179. timeout = 30;
  180. cookiePath = "/";
  181. protection = FormsProtectionEnum.All;
  182. }
  183. initialized = true;
  184. }
  185. }
  186. [MonoTODO]
  187. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  188. {
  189. throw new NotImplementedException ();
  190. }
  191. [MonoTODO]
  192. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  193. {
  194. throw new NotImplementedException ();
  195. }
  196. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  197. {
  198. if (tOld == null)
  199. return null;
  200. DateTime now = DateTime.Now;
  201. TimeSpan toIssue = now - tOld.IssueDate;
  202. TimeSpan toExpiration = tOld.Expiration - now;
  203. if (toExpiration > toIssue)
  204. return tOld;
  205. FormsAuthenticationTicket tNew = tOld.Clone ();
  206. tNew.SetDates (now, now - toExpiration + toIssue);
  207. return tNew;
  208. }
  209. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  210. {
  211. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  212. }
  213. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  214. {
  215. HttpContext context = HttpContext.Current;
  216. if (context == null)
  217. throw new HttpException ("Context is null!");
  218. HttpResponse response = context.Response;
  219. if (response == null)
  220. throw new HttpException ("Response is null!");
  221. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  222. }
  223. public static void SignOut ()
  224. {
  225. Initialize ();
  226. HttpContext context = HttpContext.Current;
  227. if (context == null)
  228. throw new HttpException ("Context is null!");
  229. HttpResponse response = context.Response;
  230. if (response == null)
  231. throw new HttpException ("Response is null!");
  232. response.Cookies.MakeCookieExpire (cookieName, cookiePath);
  233. }
  234. public static string FormsCookieName
  235. {
  236. get {
  237. Initialize ();
  238. return cookieName;
  239. }
  240. }
  241. public static string FormsCookiePath
  242. {
  243. get {
  244. Initialize ();
  245. return cookiePath;
  246. }
  247. }
  248. }
  249. }