FormsAuthentication.cs 9.5 KB

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