FormsAuthentication.cs 9.1 KB

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