FormsAuthentication.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.IO;
  32. using System.Security.Cryptography;
  33. using System.Text;
  34. using System.Web;
  35. using System.Web.Configuration;
  36. using System.Web.Util;
  37. namespace System.Web.Security
  38. {
  39. public sealed class FormsAuthentication
  40. {
  41. static string authConfigPath = "system.web/authentication";
  42. static bool initialized;
  43. static string cookieName;
  44. static string cookiePath;
  45. static int timeout;
  46. static FormsProtectionEnum protection;
  47. #if NET_1_1
  48. static bool requireSSL;
  49. static bool slidingExpiration;
  50. #endif
  51. // same names and order used in xsp
  52. static string [] indexFiles = { "index.aspx",
  53. "Default.aspx",
  54. "default.aspx",
  55. "index.html",
  56. "index.htm" };
  57. public static bool Authenticate (string name, string password)
  58. {
  59. if (name == null || password == null)
  60. return false;
  61. Initialize ();
  62. HttpContext context = HttpContext.Current;
  63. if (context == null)
  64. throw new HttpException ("Context is null!");
  65. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  66. Hashtable users = config.CredentialUsers;
  67. string stored = users [name] as string;
  68. if (stored == null)
  69. return false;
  70. switch (config.PasswordFormat) {
  71. case FormsAuthPasswordFormat.Clear:
  72. /* Do nothing */
  73. break;
  74. case FormsAuthPasswordFormat.MD5:
  75. stored = HashPasswordForStoringInConfigFile (stored, "MD5");
  76. break;
  77. case FormsAuthPasswordFormat.SHA1:
  78. stored = HashPasswordForStoringInConfigFile (stored, "SHA1");
  79. break;
  80. }
  81. return (password == stored);
  82. }
  83. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  84. {
  85. if (encryptedTicket == null || encryptedTicket == String.Empty)
  86. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  87. Initialize ();
  88. byte [] bytes = MachineKeyConfigHandler.GetBytes (encryptedTicket, encryptedTicket.Length);
  89. string decrypted = Encoding.ASCII.GetString (bytes);
  90. FormsAuthenticationTicket ticket = null;
  91. try {
  92. string [] values = decrypted.Split ((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7);
  93. if (values.Length != 8)
  94. throw new Exception (values.Length + " " + encryptedTicket);
  95. ticket = new FormsAuthenticationTicket (Int32.Parse (values [0]),
  96. values [1],
  97. new DateTime (Int64.Parse (values [2])),
  98. new DateTime (Int64.Parse (values [3])),
  99. (values [4] == "1"),
  100. values [5],
  101. values [6]);
  102. } catch (Exception) {
  103. ticket = null;
  104. }
  105. return ticket;
  106. }
  107. public static string Encrypt (FormsAuthenticationTicket ticket)
  108. {
  109. if (ticket == null)
  110. throw new ArgumentNullException ("ticket");
  111. Initialize ();
  112. StringBuilder allTicket = new StringBuilder ();
  113. allTicket.Append (ticket.Version);
  114. allTicket.Append ('\u0001');
  115. allTicket.Append (ticket.Name);
  116. allTicket.Append ('\u0002');
  117. allTicket.Append (ticket.IssueDate.Ticks);
  118. allTicket.Append ('\u0003');
  119. allTicket.Append (ticket.Expiration.Ticks);
  120. allTicket.Append ('\u0004');
  121. allTicket.Append (ticket.IsPersistent ? '1' : '0');
  122. allTicket.Append ('\u0005');
  123. allTicket.Append (ticket.UserData);
  124. allTicket.Append ('\u0006');
  125. allTicket.Append (ticket.CookiePath);
  126. allTicket.Append ('\u0007');
  127. //if (protection == FormsProtectionEnum.None)
  128. return GetHexString (allTicket.ToString ());
  129. //TODO: encrypt and validate
  130. }
  131. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  132. {
  133. return GetAuthCookie (userName, createPersistentCookie, null);
  134. }
  135. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  136. {
  137. Initialize ();
  138. if (userName == null)
  139. userName = String.Empty;
  140. if (strCookiePath == null || strCookiePath.Length == 0)
  141. strCookiePath = cookiePath;
  142. DateTime now = DateTime.Now;
  143. DateTime then;
  144. if (createPersistentCookie)
  145. then = now.AddYears (50);
  146. else
  147. then = now.AddMinutes (timeout);
  148. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  149. userName,
  150. now,
  151. then,
  152. createPersistentCookie,
  153. String.Empty,
  154. cookiePath);
  155. if (!createPersistentCookie)
  156. then = DateTime.MinValue;
  157. return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  158. }
  159. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  160. {
  161. if (userName == null)
  162. return null;
  163. //TODO: what's createPersistentCookie used for?
  164. Initialize ();
  165. HttpRequest request = HttpContext.Current.Request;
  166. string returnUrl = request ["RETURNURL"];
  167. if (returnUrl != null)
  168. return returnUrl;
  169. returnUrl = request.ApplicationPath;
  170. string apppath = request.PhysicalApplicationPath;
  171. bool found = false;
  172. foreach (string indexFile in indexFiles) {
  173. string filePath = Path.Combine (apppath, indexFile);
  174. if (File.Exists (filePath)) {
  175. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  176. found = true;
  177. break;
  178. }
  179. }
  180. if (!found)
  181. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  182. return returnUrl;
  183. }
  184. static string GetHexString (string str)
  185. {
  186. return GetHexString (Encoding.ASCII.GetBytes (str));
  187. }
  188. static string GetHexString (byte [] bytes)
  189. {
  190. StringBuilder result = new StringBuilder (bytes.Length * 2);
  191. foreach (byte b in bytes)
  192. result.AppendFormat ("{0:x2}", (int) b);
  193. return result.ToString ();
  194. }
  195. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  196. {
  197. if (password == null)
  198. throw new ArgumentNullException ("password");
  199. if (passwordFormat == null)
  200. throw new ArgumentNullException ("passwordFormat");
  201. byte [] bytes;
  202. if (String.Compare (passwordFormat, "MD5", true) == 0) {
  203. bytes = MD5.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
  204. } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
  205. bytes = SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
  206. } else {
  207. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  208. }
  209. return GetHexString (bytes);
  210. }
  211. public static void Initialize ()
  212. {
  213. if (initialized)
  214. return;
  215. lock (typeof (FormsAuthentication)) {
  216. if (initialized)
  217. return;
  218. HttpContext context = HttpContext.Current;
  219. if (context == null)
  220. throw new HttpException ("Context is null!");
  221. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  222. if (authConfig != null) {
  223. cookieName = authConfig.CookieName;
  224. timeout = authConfig.Timeout;
  225. cookiePath = authConfig.CookiePath;
  226. protection = authConfig.Protection;
  227. #if NET_1_1
  228. requireSSL = authConfig.RequireSSL;
  229. slidingExpiration = authConfig.SlidingExpiration;
  230. #endif
  231. } else {
  232. cookieName = ".MONOAUTH";
  233. timeout = 30;
  234. cookiePath = "/";
  235. protection = FormsProtectionEnum.All;
  236. #if NET_1_1
  237. slidingExpiration = true;
  238. #endif
  239. }
  240. initialized = true;
  241. }
  242. }
  243. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  244. {
  245. RedirectFromLoginPage (userName, createPersistentCookie, null);
  246. }
  247. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  248. {
  249. if (userName == null)
  250. return;
  251. Initialize ();
  252. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  253. HttpResponse resp = HttpContext.Current.Response;
  254. resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  255. }
  256. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  257. {
  258. if (tOld == null)
  259. return null;
  260. DateTime now = DateTime.Now;
  261. TimeSpan toIssue = now - tOld.IssueDate;
  262. TimeSpan toExpiration = tOld.Expiration - now;
  263. if (toExpiration > toIssue)
  264. return tOld;
  265. FormsAuthenticationTicket tNew = tOld.Clone ();
  266. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  267. return tNew;
  268. }
  269. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  270. {
  271. Initialize ();
  272. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  273. }
  274. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  275. {
  276. HttpContext context = HttpContext.Current;
  277. if (context == null)
  278. throw new HttpException ("Context is null!");
  279. HttpResponse response = context.Response;
  280. if (response == null)
  281. throw new HttpException ("Response is null!");
  282. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  283. }
  284. public static void SignOut ()
  285. {
  286. Initialize ();
  287. HttpContext context = HttpContext.Current;
  288. if (context == null)
  289. throw new HttpException ("Context is null!");
  290. HttpResponse response = context.Response;
  291. if (response == null)
  292. throw new HttpException ("Response is null!");
  293. response.Cookies.MakeCookieExpire (cookieName, cookiePath);
  294. }
  295. public static string FormsCookieName
  296. {
  297. get {
  298. Initialize ();
  299. return cookieName;
  300. }
  301. }
  302. public static string FormsCookiePath
  303. {
  304. get {
  305. Initialize ();
  306. return cookiePath;
  307. }
  308. }
  309. #if NET_1_1
  310. public static bool RequireSSL {
  311. get {
  312. Initialize ();
  313. return requireSSL;
  314. }
  315. }
  316. public static bool SlidingExpiration {
  317. get {
  318. Initialize ();
  319. return slidingExpiration;
  320. }
  321. }
  322. #endif
  323. }
  324. }