FormsAuthentication.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. // Copyright (c) 2005 Novell, Inc (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System.Collections;
  31. using System.IO;
  32. using System.Security.Cryptography;
  33. using System.Security.Permissions;
  34. using System.Text;
  35. using System.Web;
  36. using System.Web.Configuration;
  37. using System.Web.Util;
  38. using System.Globalization;
  39. namespace System.Web.Security
  40. {
  41. // CAS - no InheritanceDemand here as the class is sealed
  42. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  43. public sealed class FormsAuthentication
  44. {
  45. const int MD5_hash_size = 16;
  46. const int SHA1_hash_size = 20;
  47. static string authConfigPath = "system.web/authentication";
  48. static string machineKeyConfigPath = "system.web/machineKey";
  49. #if TARGET_J2EE
  50. const string Forms_initialized = "Forms.initialized";
  51. const string Forms_cookieName = "Forms.cookieName";
  52. const string Forms_cookiePath = "Forms.cookiePath";
  53. const string Forms_timeout = "Forms.timeout";
  54. const string Forms_protection = "Forms.protection";
  55. const string Forms_init_vector = "Forms.init_vector";
  56. static bool initialized
  57. {
  58. get {
  59. object o = AppDomain.CurrentDomain.GetData (Forms_initialized);
  60. return o != null ? (bool) o : false;
  61. }
  62. set { AppDomain.CurrentDomain.SetData (Forms_initialized, value); }
  63. }
  64. static string cookieName
  65. {
  66. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookieName); }
  67. set { AppDomain.CurrentDomain.SetData (Forms_cookieName, value); }
  68. }
  69. static string cookiePath
  70. {
  71. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookiePath); }
  72. set { AppDomain.CurrentDomain.SetData (Forms_cookiePath, value); }
  73. }
  74. static int timeout
  75. {
  76. get {
  77. object o = AppDomain.CurrentDomain.GetData (Forms_timeout);
  78. return o != null ? (int) o : 0;
  79. }
  80. set { AppDomain.CurrentDomain.SetData (Forms_timeout, value); }
  81. }
  82. static FormsProtectionEnum protection
  83. {
  84. get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
  85. set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
  86. }
  87. static byte [] init_vector
  88. {
  89. get { return (byte []) AppDomain.CurrentDomain.GetData (Forms_init_vector); }
  90. set { AppDomain.CurrentDomain.SetData (Forms_init_vector, value); }
  91. }
  92. static object locker = new object ();
  93. #else
  94. static bool initialized;
  95. static string cookieName;
  96. static string cookiePath;
  97. static int timeout;
  98. static FormsProtectionEnum protection;
  99. static object locker = new object ();
  100. static byte [] init_vector; // initialization vector used for 3DES
  101. #endif
  102. #if NET_1_1
  103. #if TARGET_J2EE
  104. const string Forms_requireSSL = "Forms.requireSSL";
  105. const string Forms_slidingExpiration = "Forms.slidingExpiration";
  106. static bool requireSSL
  107. {
  108. get {
  109. object o = AppDomain.CurrentDomain.GetData (Forms_requireSSL);
  110. return o != null ? (bool) o : false;
  111. }
  112. set { AppDomain.CurrentDomain.SetData (Forms_requireSSL, value); }
  113. }
  114. static bool slidingExpiration
  115. {
  116. get {
  117. object o = AppDomain.CurrentDomain.GetData (Forms_slidingExpiration);
  118. return o != null ? (bool) o : false;
  119. }
  120. set { AppDomain.CurrentDomain.SetData (Forms_slidingExpiration, value); }
  121. }
  122. #else
  123. static bool requireSSL;
  124. static bool slidingExpiration;
  125. #endif
  126. #endif
  127. #if NET_2_0
  128. #if TARGET_J2EE
  129. const string Forms_cookie_domain = "Forms.cookie_domain";
  130. const string Forms_cookie_mode = "Forms.cookie_mode";
  131. const string Forms_cookies_supported = "Forms.cookies_supported";
  132. const string Forms_default_url = "Forms.default_url";
  133. const string Forms_enable_crossapp_redirects = "Forms.enable_crossapp_redirects";
  134. const string Forms_login_url = "Forms.login_url";
  135. static string cookie_domain
  136. {
  137. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookie_domain); }
  138. set { AppDomain.CurrentDomain.SetData (Forms_cookie_domain, value); }
  139. }
  140. static HttpCookieMode cookie_mode
  141. {
  142. get { return (HttpCookieMode) AppDomain.CurrentDomain.GetData (Forms_cookie_mode); }
  143. set { AppDomain.CurrentDomain.SetData (Forms_cookie_mode, value); }
  144. }
  145. static bool cookies_supported
  146. {
  147. get {
  148. object o = AppDomain.CurrentDomain.GetData (Forms_cookies_supported);
  149. return o != null ? (bool) o : false;
  150. }
  151. set { AppDomain.CurrentDomain.SetData (Forms_cookies_supported, value); }
  152. }
  153. static string default_url
  154. {
  155. get { return (string) AppDomain.CurrentDomain.GetData (Forms_default_url); }
  156. set { AppDomain.CurrentDomain.SetData (Forms_default_url, value); }
  157. }
  158. static bool enable_crossapp_redirects
  159. {
  160. get {
  161. object o = AppDomain.CurrentDomain.GetData (Forms_enable_crossapp_redirects);
  162. return o != null ? (bool) o : false;
  163. }
  164. set { AppDomain.CurrentDomain.SetData (Forms_enable_crossapp_redirects, value); }
  165. }
  166. static string login_url
  167. {
  168. get { return (string) AppDomain.CurrentDomain.GetData (Forms_login_url); }
  169. set { AppDomain.CurrentDomain.SetData (Forms_login_url, value); }
  170. }
  171. #else
  172. static string cookie_domain;
  173. static HttpCookieMode cookie_mode;
  174. static bool cookies_supported;
  175. static string default_url;
  176. static bool enable_crossapp_redirects;
  177. static string login_url;
  178. #endif
  179. #endif
  180. // same names and order used in xsp
  181. static string [] indexFiles = { "index.aspx",
  182. "Default.aspx",
  183. "default.aspx",
  184. "index.html",
  185. "index.htm" };
  186. public FormsAuthentication ()
  187. {
  188. }
  189. public static bool Authenticate (string name, string password)
  190. {
  191. if (name == null || password == null)
  192. return false;
  193. Initialize ();
  194. HttpContext context = HttpContext.Current;
  195. if (context == null)
  196. throw new HttpException ("Context is null!");
  197. name = name.ToLower (Helpers.InvariantCulture);
  198. #if NET_2_0
  199. AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
  200. FormsAuthenticationCredentials config = section.Forms.Credentials;
  201. FormsAuthenticationUser user = config.Users[name];
  202. string stored = null;
  203. if (user != null)
  204. stored = user.Password;
  205. #else
  206. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  207. Hashtable users = config.CredentialUsers;
  208. string stored = users [name] as string;
  209. #endif
  210. if (stored == null)
  211. return false;
  212. bool caseInsensitive = true;
  213. switch (config.PasswordFormat) {
  214. case FormsAuthPasswordFormat.Clear:
  215. caseInsensitive = false;
  216. /* Do nothing */
  217. break;
  218. case FormsAuthPasswordFormat.MD5:
  219. password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
  220. break;
  221. case FormsAuthPasswordFormat.SHA1:
  222. password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
  223. break;
  224. }
  225. return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
  226. }
  227. #if NET_2_0
  228. static byte [] GetDecryptionKey (MachineKeySection config)
  229. {
  230. return MachineKeySectionUtils.DecryptionKey192Bits (config);
  231. }
  232. #else
  233. static byte [] GetDecryptionKey (MachineKeyConfig config)
  234. {
  235. return config.DecryptionKey192Bits;
  236. }
  237. #endif
  238. static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
  239. {
  240. if (protection == FormsProtectionEnum.None)
  241. return FormsAuthenticationTicket.FromByteArray (bytes);
  242. #if NET_2_0
  243. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  244. #else
  245. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  246. #endif
  247. bool all = (protection == FormsProtectionEnum.All);
  248. byte [] result = bytes;
  249. if (all || protection == FormsProtectionEnum.Encryption) {
  250. ICryptoTransform decryptor;
  251. decryptor = TripleDES.Create ().CreateDecryptor (GetDecryptionKey (config), init_vector);
  252. result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
  253. bytes = null;
  254. }
  255. if (all || protection == FormsProtectionEnum.Validation) {
  256. int count;
  257. MachineKeyValidation validationType;
  258. #if NET_2_0
  259. validationType = config.Validation;
  260. #else
  261. validationType = config.ValidationType;
  262. #endif
  263. if (validationType == MachineKeyValidation.MD5)
  264. count = MD5_hash_size;
  265. else
  266. count = SHA1_hash_size; // 3DES and SHA1
  267. #if NET_2_0
  268. byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
  269. #else
  270. byte [] vk = config.ValidationKey;
  271. #endif
  272. byte [] mix = new byte [result.Length - count + vk.Length];
  273. Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
  274. Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
  275. byte [] hash = null;
  276. switch (validationType) {
  277. case MachineKeyValidation.MD5:
  278. hash = MD5.Create ().ComputeHash (mix);
  279. break;
  280. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  281. case MachineKeyValidation.TripleDES:
  282. case MachineKeyValidation.SHA1:
  283. hash = SHA1.Create ().ComputeHash (mix);
  284. break;
  285. }
  286. if (result.Length < count)
  287. throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
  288. int i, k;
  289. for (i = result.Length - count, k = 0; k < count; i++, k++) {
  290. if (result [i] != hash [k])
  291. throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
  292. }
  293. }
  294. return FormsAuthenticationTicket.FromByteArray (result);
  295. }
  296. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  297. {
  298. if (encryptedTicket == null || encryptedTicket == String.Empty)
  299. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  300. Initialize ();
  301. FormsAuthenticationTicket ticket;
  302. #if NET_2_0
  303. byte [] bytes = MachineKeySectionUtils.GetBytes (encryptedTicket, encryptedTicket.Length);
  304. #else
  305. byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
  306. #endif
  307. try {
  308. ticket = Decrypt2 (bytes);
  309. } catch (Exception) {
  310. ticket = null;
  311. }
  312. return ticket;
  313. }
  314. public static string Encrypt (FormsAuthenticationTicket ticket)
  315. {
  316. if (ticket == null)
  317. throw new ArgumentNullException ("ticket");
  318. Initialize ();
  319. byte [] ticket_bytes = ticket.ToByteArray ();
  320. if (protection == FormsProtectionEnum.None)
  321. return GetHexString (ticket_bytes);
  322. byte [] result = ticket_bytes;
  323. #if NET_2_0
  324. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  325. #else
  326. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  327. #endif
  328. bool all = (protection == FormsProtectionEnum.All);
  329. if (all || protection == FormsProtectionEnum.Validation) {
  330. byte [] valid_bytes = null;
  331. #if NET_2_0
  332. byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
  333. #else
  334. byte [] vk = config.ValidationKey;
  335. #endif
  336. byte [] mix = new byte [ticket_bytes.Length + vk.Length];
  337. Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
  338. Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
  339. switch (
  340. #if NET_2_0
  341. config.Validation
  342. #else
  343. config.ValidationType
  344. #endif
  345. ) {
  346. case MachineKeyValidation.MD5:
  347. valid_bytes = MD5.Create ().ComputeHash (mix);
  348. break;
  349. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  350. case MachineKeyValidation.TripleDES:
  351. case MachineKeyValidation.SHA1:
  352. valid_bytes = SHA1.Create ().ComputeHash (mix);
  353. break;
  354. }
  355. int tlen = ticket_bytes.Length;
  356. int vlen = valid_bytes.Length;
  357. result = new byte [tlen + vlen];
  358. Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
  359. Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
  360. }
  361. if (all || protection == FormsProtectionEnum.Encryption) {
  362. ICryptoTransform encryptor;
  363. encryptor = TripleDES.Create ().CreateEncryptor (GetDecryptionKey (config), init_vector);
  364. result = encryptor.TransformFinalBlock (result, 0, result.Length);
  365. }
  366. return GetHexString (result);
  367. }
  368. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  369. {
  370. return GetAuthCookie (userName, createPersistentCookie, null);
  371. }
  372. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  373. {
  374. Initialize ();
  375. if (userName == null)
  376. userName = String.Empty;
  377. if (strCookiePath == null || strCookiePath.Length == 0)
  378. strCookiePath = cookiePath;
  379. DateTime now = DateTime.Now;
  380. DateTime then;
  381. if (createPersistentCookie)
  382. then = now.AddYears (50);
  383. else
  384. then = now.AddMinutes (timeout);
  385. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  386. userName,
  387. now,
  388. then,
  389. createPersistentCookie,
  390. String.Empty,
  391. cookiePath);
  392. if (!createPersistentCookie)
  393. then = DateTime.MinValue;
  394. HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  395. if (requireSSL)
  396. cookie.Secure = true;
  397. #if NET_2_0
  398. if (!String.IsNullOrEmpty (cookie_domain))
  399. cookie.Domain = cookie_domain;
  400. #endif
  401. return cookie;
  402. }
  403. internal static string ReturnUrl
  404. {
  405. get { return HttpContext.Current.Request ["RETURNURL"]; }
  406. }
  407. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  408. {
  409. if (userName == null)
  410. return null;
  411. Initialize ();
  412. HttpRequest request = HttpContext.Current.Request;
  413. string returnUrl = ReturnUrl;
  414. if (returnUrl != null)
  415. return returnUrl;
  416. returnUrl = request.ApplicationPath;
  417. string apppath = request.PhysicalApplicationPath;
  418. bool found = false;
  419. foreach (string indexFile in indexFiles) {
  420. string filePath = Path.Combine (apppath, indexFile);
  421. if (File.Exists (filePath)) {
  422. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  423. found = true;
  424. break;
  425. }
  426. }
  427. if (!found)
  428. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  429. return returnUrl;
  430. }
  431. static string GetHexString (byte [] bytes)
  432. {
  433. const int letterPart = 55;
  434. const int numberPart = 48;
  435. char [] result = new char [bytes.Length * 2];
  436. for (int i = 0; i < bytes.Length; i++) {
  437. int tmp = (int) bytes [i];
  438. int second = tmp & 15;
  439. int first = (tmp >> 4) & 15;
  440. result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
  441. result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
  442. }
  443. return new string (result);
  444. }
  445. static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
  446. {
  447. if (password == null)
  448. throw new ArgumentNullException ("password");
  449. byte [] bytes;
  450. switch (passwordFormat) {
  451. case FormsAuthPasswordFormat.MD5:
  452. bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  453. break;
  454. case FormsAuthPasswordFormat.SHA1:
  455. bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  456. break;
  457. default:
  458. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  459. }
  460. return GetHexString (bytes);
  461. }
  462. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  463. {
  464. if (password == null)
  465. throw new ArgumentNullException ("password");
  466. if (passwordFormat == null)
  467. throw new ArgumentNullException ("passwordFormat");
  468. if (String.Compare (passwordFormat, "MD5", true, Helpers.InvariantCulture) == 0) {
  469. return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
  470. } else if (String.Compare (passwordFormat, "SHA1", true, Helpers.InvariantCulture) == 0) {
  471. return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
  472. } else {
  473. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  474. }
  475. }
  476. public static void Initialize ()
  477. {
  478. if (initialized)
  479. return;
  480. lock (locker) {
  481. if (initialized)
  482. return;
  483. #if NET_2_0
  484. AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
  485. FormsAuthenticationConfiguration config = section.Forms;
  486. cookieName = config.Name;
  487. timeout = (int)config.Timeout.TotalMinutes;
  488. cookiePath = config.Path;
  489. protection = config.Protection;
  490. requireSSL = config.RequireSSL;
  491. slidingExpiration = config.SlidingExpiration;
  492. cookie_domain = config.Domain;
  493. cookie_mode = config.Cookieless;
  494. cookies_supported = true; /* XXX ? */
  495. default_url = MapUrl(config.DefaultUrl);
  496. enable_crossapp_redirects = config.EnableCrossAppRedirects;
  497. login_url = MapUrl(config.LoginUrl);
  498. #else
  499. HttpContext context = HttpContext.Current;
  500. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  501. if (authConfig != null) {
  502. cookieName = authConfig.CookieName;
  503. timeout = authConfig.Timeout;
  504. cookiePath = authConfig.CookiePath;
  505. protection = authConfig.Protection;
  506. #if NET_1_1
  507. requireSSL = authConfig.RequireSSL;
  508. slidingExpiration = authConfig.SlidingExpiration;
  509. #endif
  510. } else {
  511. cookieName = ".MONOAUTH";
  512. timeout = 30;
  513. cookiePath = "/";
  514. protection = FormsProtectionEnum.All;
  515. #if NET_1_1
  516. slidingExpiration = true;
  517. #endif
  518. }
  519. #endif
  520. // IV is 8 bytes long for 3DES
  521. init_vector = new byte [8];
  522. int len = cookieName.Length;
  523. for (int i = 0; i < 8; i++) {
  524. if (i >= len)
  525. break;
  526. init_vector [i] = (byte) cookieName [i];
  527. }
  528. initialized = true;
  529. }
  530. }
  531. #if NET_2_0
  532. static string MapUrl (string url) {
  533. if (UrlUtils.IsRelativeUrl (url))
  534. return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
  535. else
  536. return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
  537. }
  538. #endif
  539. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  540. {
  541. RedirectFromLoginPage (userName, createPersistentCookie, null);
  542. }
  543. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  544. {
  545. if (userName == null)
  546. return;
  547. Initialize ();
  548. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  549. Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  550. }
  551. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  552. {
  553. if (tOld == null)
  554. return null;
  555. DateTime now = DateTime.Now;
  556. TimeSpan toIssue = now - tOld.IssueDate;
  557. TimeSpan toExpiration = tOld.Expiration - now;
  558. if (toExpiration > toIssue)
  559. return tOld;
  560. FormsAuthenticationTicket tNew = tOld.Clone ();
  561. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  562. return tNew;
  563. }
  564. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  565. {
  566. Initialize ();
  567. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  568. }
  569. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  570. {
  571. HttpContext context = HttpContext.Current;
  572. if (context == null)
  573. throw new HttpException ("Context is null!");
  574. HttpResponse response = context.Response;
  575. if (response == null)
  576. throw new HttpException ("Response is null!");
  577. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  578. }
  579. public static void SignOut ()
  580. {
  581. Initialize ();
  582. HttpContext context = HttpContext.Current;
  583. if (context == null)
  584. throw new HttpException ("Context is null!");
  585. HttpResponse response = context.Response;
  586. if (response == null)
  587. throw new HttpException ("Response is null!");
  588. HttpCookieCollection cc = response.Cookies;
  589. cc.Remove (cookieName);
  590. HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
  591. expiration_cookie.Expires = new DateTime (1999, 10, 12);
  592. expiration_cookie.Path = cookiePath;
  593. #if NET_2_0
  594. if (!String.IsNullOrEmpty (cookie_domain))
  595. expiration_cookie.Domain = cookie_domain;
  596. #endif
  597. cc.Add (expiration_cookie);
  598. #if NET_2_0
  599. Roles.DeleteCookie ();
  600. #endif
  601. }
  602. public static string FormsCookieName
  603. {
  604. get {
  605. Initialize ();
  606. return cookieName;
  607. }
  608. }
  609. public static string FormsCookiePath
  610. {
  611. get {
  612. Initialize ();
  613. return cookiePath;
  614. }
  615. }
  616. #if NET_1_1
  617. public static bool RequireSSL {
  618. get {
  619. Initialize ();
  620. return requireSSL;
  621. }
  622. }
  623. public static bool SlidingExpiration {
  624. get {
  625. Initialize ();
  626. return slidingExpiration;
  627. }
  628. }
  629. #endif
  630. #if NET_2_0
  631. public static string CookieDomain {
  632. get { Initialize (); return cookie_domain; }
  633. }
  634. public static HttpCookieMode CookieMode {
  635. get { Initialize (); return cookie_mode; }
  636. }
  637. public static bool CookiesSupported {
  638. get { Initialize (); return cookies_supported; }
  639. }
  640. public static string DefaultUrl {
  641. get { Initialize (); return default_url; }
  642. }
  643. public static bool EnableCrossAppRedirects {
  644. get { Initialize (); return enable_crossapp_redirects; }
  645. }
  646. public static string LoginUrl {
  647. get { Initialize (); return login_url; }
  648. }
  649. public static void RedirectToLoginPage ()
  650. {
  651. Redirect (LoginUrl);
  652. }
  653. [MonoTODO ("needs more tests")]
  654. public static void RedirectToLoginPage (string extraQueryString)
  655. {
  656. // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
  657. Redirect (LoginUrl + "?" + extraQueryString);
  658. }
  659. static void Redirect (string url)
  660. {
  661. HttpContext.Current.Response.Redirect (url);
  662. }
  663. #endif
  664. static void Redirect (string url, bool end)
  665. {
  666. HttpContext.Current.Response.Redirect (url, end);
  667. }
  668. }
  669. }