FormsAuthentication.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. string decrypted = Encoding.ASCII.GetString (bytes);
  66. FormsAuthenticationTicket ticket = null;
  67. try {
  68. string [] values = decrypted.Split ((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7);
  69. if (values.Length != 8)
  70. throw new Exception (values.Length + " " + encryptedTicket);
  71. ticket = new FormsAuthenticationTicket (Int32.Parse (values [0]),
  72. values [1],
  73. new DateTime (Int64.Parse (values [2])),
  74. new DateTime (Int64.Parse (values [3])),
  75. (values [4] == "1"),
  76. values [5],
  77. values [6]);
  78. } catch (Exception e) {
  79. ticket = null;
  80. }
  81. return ticket;
  82. }
  83. public static string Encrypt (FormsAuthenticationTicket ticket)
  84. {
  85. if (ticket == null)
  86. throw new ArgumentNullException ("ticket");
  87. Initialize ();
  88. StringBuilder allTicket = new StringBuilder ();
  89. allTicket.Append (ticket.Version);
  90. allTicket.Append ('\u0001');
  91. allTicket.Append (ticket.Name);
  92. allTicket.Append ('\u0002');
  93. allTicket.Append (ticket.IssueDate.Ticks);
  94. allTicket.Append ('\u0003');
  95. allTicket.Append (ticket.Expiration.Ticks);
  96. allTicket.Append ('\u0004');
  97. allTicket.Append (ticket.IsPersistent ? '1' : '0');
  98. allTicket.Append ('\u0005');
  99. allTicket.Append (ticket.UserData);
  100. allTicket.Append ('\u0006');
  101. allTicket.Append (ticket.CookiePath);
  102. allTicket.Append ('\u0007');
  103. //if (protection == FormsProtectionEnum.None)
  104. return GetHexString (allTicket.ToString ());
  105. //TODO: encrypt and validate
  106. }
  107. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  108. {
  109. return GetAuthCookie (userName, createPersistentCookie, null);
  110. }
  111. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  112. {
  113. Initialize ();
  114. if (userName == null)
  115. userName = String.Empty;
  116. if (strCookiePath == null || strCookiePath.Length == 0)
  117. strCookiePath = cookiePath;
  118. DateTime now = DateTime.Now;
  119. DateTime then;
  120. if (createPersistentCookie)
  121. then = now.AddYears (50);
  122. else
  123. then = now.AddMinutes (timeout);
  124. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  125. userName,
  126. now,
  127. then,
  128. createPersistentCookie,
  129. String.Empty,
  130. cookiePath);
  131. if (!createPersistentCookie)
  132. then = DateTime.MinValue;
  133. return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  134. }
  135. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  136. {
  137. if (userName == null)
  138. return null;
  139. //TODO: what's createPersistentCookie used for?
  140. Initialize ();
  141. HttpRequest request = HttpContext.Current.Request;
  142. string returnUrl = request ["RETURNURL"];
  143. if (returnUrl != null)
  144. return returnUrl;
  145. returnUrl = request.ApplicationPath;
  146. string apppath = request.PhysicalApplicationPath;
  147. bool found = false;
  148. foreach (string indexFile in indexFiles) {
  149. string filePath = Path.Combine (apppath, indexFile);
  150. if (File.Exists (filePath)) {
  151. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  152. found = true;
  153. break;
  154. }
  155. }
  156. if (!found)
  157. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  158. return returnUrl;
  159. }
  160. static string GetHexString (string str)
  161. {
  162. return GetHexString (Encoding.ASCII.GetBytes (str));
  163. }
  164. static string GetHexString (byte [] bytes)
  165. {
  166. StringBuilder result = new StringBuilder (bytes.Length * 2);
  167. foreach (byte b in bytes)
  168. result.AppendFormat ("{0:x2}", (int) b);
  169. return result.ToString ();
  170. }
  171. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  172. {
  173. if (password == null)
  174. throw new ArgumentNullException ("password");
  175. if (passwordFormat == null)
  176. throw new ArgumentNullException ("passwordFormat");
  177. byte [] bytes;
  178. if (String.Compare (passwordFormat, "MD5", true) == 0) {
  179. bytes = MD5.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
  180. } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
  181. bytes = SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
  182. } else {
  183. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  184. }
  185. return GetHexString (bytes);
  186. }
  187. public static void Initialize ()
  188. {
  189. if (initialized)
  190. return;
  191. lock (typeof (FormsAuthentication)) {
  192. if (initialized)
  193. return;
  194. HttpContext context = HttpContext.Current;
  195. if (context == null)
  196. throw new HttpException ("Context is null!");
  197. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  198. if (authConfig != null) {
  199. cookieName = authConfig.CookieName;
  200. timeout = authConfig.Timeout;
  201. cookiePath = authConfig.CookiePath;
  202. protection = authConfig.Protection;
  203. } else {
  204. cookieName = ".MONOAUTH";
  205. timeout = 30;
  206. cookiePath = "/";
  207. protection = FormsProtectionEnum.All;
  208. }
  209. initialized = true;
  210. }
  211. }
  212. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  213. {
  214. RedirectFromLoginPage (userName, createPersistentCookie, null);
  215. }
  216. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  217. {
  218. if (userName == null)
  219. return;
  220. Initialize ();
  221. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  222. HttpResponse resp = HttpContext.Current.Response;
  223. resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  224. }
  225. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  226. {
  227. if (tOld == null)
  228. return null;
  229. DateTime now = DateTime.Now;
  230. TimeSpan toIssue = now - tOld.IssueDate;
  231. TimeSpan toExpiration = tOld.Expiration - now;
  232. if (toExpiration > toIssue)
  233. return tOld;
  234. FormsAuthenticationTicket tNew = tOld.Clone ();
  235. tNew.SetDates (now, now - toExpiration + toIssue);
  236. return tNew;
  237. }
  238. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  239. {
  240. Initialize ();
  241. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  242. }
  243. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  244. {
  245. HttpContext context = HttpContext.Current;
  246. if (context == null)
  247. throw new HttpException ("Context is null!");
  248. HttpResponse response = context.Response;
  249. if (response == null)
  250. throw new HttpException ("Response is null!");
  251. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  252. }
  253. public static void SignOut ()
  254. {
  255. Initialize ();
  256. HttpContext context = HttpContext.Current;
  257. if (context == null)
  258. throw new HttpException ("Context is null!");
  259. HttpResponse response = context.Response;
  260. if (response == null)
  261. throw new HttpException ("Response is null!");
  262. response.Cookies.MakeCookieExpire (cookieName, cookiePath);
  263. }
  264. public static string FormsCookieName
  265. {
  266. get {
  267. Initialize ();
  268. return cookieName;
  269. }
  270. }
  271. public static string FormsCookiePath
  272. {
  273. get {
  274. Initialize ();
  275. return cookiePath;
  276. }
  277. }
  278. }
  279. }