FormsAuthentication.cs 11 KB

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