FormsAuthentication.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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 ();
  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. switch (config.PasswordFormat) {
  213. case FormsAuthPasswordFormat.Clear:
  214. /* Do nothing */
  215. break;
  216. case FormsAuthPasswordFormat.MD5:
  217. password = HashPasswordForStoringInConfigFile (password, "MD5");
  218. break;
  219. case FormsAuthPasswordFormat.SHA1:
  220. password = HashPasswordForStoringInConfigFile (password, "SHA1");
  221. break;
  222. }
  223. return (password == stored);
  224. }
  225. static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
  226. {
  227. if (protection == FormsProtectionEnum.None)
  228. return FormsAuthenticationTicket.FromByteArray (bytes);
  229. #if NET_2_0
  230. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  231. #else
  232. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  233. #endif
  234. bool all = (protection == FormsProtectionEnum.All);
  235. byte [] result = bytes;
  236. if (all || protection == FormsProtectionEnum.Encryption) {
  237. ICryptoTransform decryptor;
  238. decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
  239. result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
  240. bytes = null;
  241. }
  242. if (all || protection == FormsProtectionEnum.Validation) {
  243. int count;
  244. MachineKeyValidation validationType;
  245. #if NET_2_0
  246. validationType = config.Validation;
  247. #else
  248. validationType = config.ValidationType;
  249. #endif
  250. if (validationType == MachineKeyValidation.MD5)
  251. count = MD5_hash_size;
  252. else
  253. count = SHA1_hash_size; // 3DES and SHA1
  254. #if NET_2_0
  255. byte [] vk = config.ValidationKeyBytes;
  256. #else
  257. byte [] vk = config.ValidationKey;
  258. #endif
  259. byte [] mix = new byte [result.Length - count + vk.Length];
  260. Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
  261. Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
  262. byte [] hash = null;
  263. switch (validationType) {
  264. case MachineKeyValidation.MD5:
  265. hash = MD5.Create ().ComputeHash (mix);
  266. break;
  267. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  268. case MachineKeyValidation.TripleDES:
  269. case MachineKeyValidation.SHA1:
  270. hash = SHA1.Create ().ComputeHash (mix);
  271. break;
  272. }
  273. if (result.Length < count)
  274. throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
  275. int i, k;
  276. for (i = result.Length - count, k = 0; k < count; i++, k++) {
  277. if (result [i] != hash [k])
  278. throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
  279. }
  280. }
  281. return FormsAuthenticationTicket.FromByteArray (result);
  282. }
  283. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  284. {
  285. if (encryptedTicket == null || encryptedTicket == String.Empty)
  286. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  287. Initialize ();
  288. FormsAuthenticationTicket ticket;
  289. #if NET_2_0
  290. byte [] bytes = MachineKeySection.GetBytes (encryptedTicket, encryptedTicket.Length);
  291. #else
  292. byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
  293. #endif
  294. try {
  295. ticket = Decrypt2 (bytes);
  296. } catch (Exception) {
  297. ticket = null;
  298. }
  299. return ticket;
  300. }
  301. public static string Encrypt (FormsAuthenticationTicket ticket)
  302. {
  303. if (ticket == null)
  304. throw new ArgumentNullException ("ticket");
  305. Initialize ();
  306. byte [] ticket_bytes = ticket.ToByteArray ();
  307. if (protection == FormsProtectionEnum.None)
  308. return GetHexString (ticket_bytes);
  309. byte [] result = ticket_bytes;
  310. #if NET_2_0
  311. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  312. #else
  313. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  314. #endif
  315. bool all = (protection == FormsProtectionEnum.All);
  316. if (all || protection == FormsProtectionEnum.Validation) {
  317. byte [] valid_bytes = null;
  318. #if NET_2_0
  319. byte [] vk = config.ValidationKeyBytes;
  320. #else
  321. byte [] vk = config.ValidationKey;
  322. #endif
  323. byte [] mix = new byte [ticket_bytes.Length + vk.Length];
  324. Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
  325. Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
  326. switch (
  327. #if NET_2_0
  328. config.Validation
  329. #else
  330. config.ValidationType
  331. #endif
  332. ) {
  333. case MachineKeyValidation.MD5:
  334. valid_bytes = MD5.Create ().ComputeHash (mix);
  335. break;
  336. // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
  337. case MachineKeyValidation.TripleDES:
  338. case MachineKeyValidation.SHA1:
  339. valid_bytes = SHA1.Create ().ComputeHash (mix);
  340. break;
  341. }
  342. int tlen = ticket_bytes.Length;
  343. int vlen = valid_bytes.Length;
  344. result = new byte [tlen + vlen];
  345. Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
  346. Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
  347. }
  348. if (all || protection == FormsProtectionEnum.Encryption) {
  349. ICryptoTransform encryptor;
  350. encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
  351. result = encryptor.TransformFinalBlock (result, 0, result.Length);
  352. }
  353. return GetHexString (result);
  354. }
  355. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  356. {
  357. return GetAuthCookie (userName, createPersistentCookie, null);
  358. }
  359. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  360. {
  361. Initialize ();
  362. if (userName == null)
  363. userName = String.Empty;
  364. if (strCookiePath == null || strCookiePath.Length == 0)
  365. strCookiePath = cookiePath;
  366. DateTime now = DateTime.Now;
  367. DateTime then;
  368. if (createPersistentCookie)
  369. then = now.AddYears (50);
  370. else
  371. then = now.AddMinutes (timeout);
  372. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  373. userName,
  374. now,
  375. then,
  376. createPersistentCookie,
  377. String.Empty,
  378. cookiePath);
  379. if (!createPersistentCookie)
  380. then = DateTime.MinValue;
  381. HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  382. if (requireSSL)
  383. cookie.Secure = true;
  384. return cookie;
  385. }
  386. internal static string ReturnUrl
  387. {
  388. get { return HttpContext.Current.Request ["RETURNURL"]; }
  389. }
  390. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  391. {
  392. if (userName == null)
  393. return null;
  394. Initialize ();
  395. HttpRequest request = HttpContext.Current.Request;
  396. string returnUrl = ReturnUrl;
  397. if (returnUrl != null)
  398. return returnUrl;
  399. returnUrl = request.ApplicationPath;
  400. string apppath = request.PhysicalApplicationPath;
  401. bool found = false;
  402. foreach (string indexFile in indexFiles) {
  403. string filePath = Path.Combine (apppath, indexFile);
  404. if (File.Exists (filePath)) {
  405. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  406. found = true;
  407. break;
  408. }
  409. }
  410. if (!found)
  411. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  412. return returnUrl;
  413. }
  414. static string GetHexString (byte [] bytes)
  415. {
  416. const int letterPart = 55;
  417. const int numberPart = 48;
  418. char [] result = new char [bytes.Length * 2];
  419. for (int i = 0; i < bytes.Length; i++) {
  420. int tmp = (int) bytes [i];
  421. int second = tmp & 15;
  422. int first = (tmp >> 4) & 15;
  423. result [(i * 2)] = (char) (first > 9 ? letterPart + first : numberPart + first);
  424. result [(i * 2) + 1] = (char) (second > 9 ? letterPart + second : numberPart + second);
  425. }
  426. return new string (result);
  427. }
  428. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  429. {
  430. if (password == null)
  431. throw new ArgumentNullException ("password");
  432. if (passwordFormat == null)
  433. throw new ArgumentNullException ("passwordFormat");
  434. byte [] bytes;
  435. if (String.Compare (passwordFormat, "MD5", true, CultureInfo.InvariantCulture) == 0) {
  436. bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  437. } else if (String.Compare (passwordFormat, "SHA1", true, CultureInfo.InvariantCulture) == 0) {
  438. bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  439. } else {
  440. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  441. }
  442. return GetHexString (bytes);
  443. }
  444. public static void Initialize ()
  445. {
  446. if (initialized)
  447. return;
  448. lock (locker) {
  449. if (initialized)
  450. return;
  451. #if NET_2_0
  452. AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
  453. FormsAuthenticationConfiguration config = section.Forms;
  454. cookieName = config.Name;
  455. timeout = (int)config.Timeout.TotalMinutes;
  456. cookiePath = config.Path;
  457. protection = config.Protection;
  458. requireSSL = config.RequireSSL;
  459. slidingExpiration = config.SlidingExpiration;
  460. cookie_domain = config.Domain;
  461. cookie_mode = config.Cookieless;
  462. cookies_supported = true; /* XXX ? */
  463. default_url = MapUrl(config.DefaultUrl);
  464. enable_crossapp_redirects = config.EnableCrossAppRedirects;
  465. login_url = MapUrl(config.LoginUrl);
  466. #else
  467. HttpContext context = HttpContext.Current;
  468. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  469. if (authConfig != null) {
  470. cookieName = authConfig.CookieName;
  471. timeout = authConfig.Timeout;
  472. cookiePath = authConfig.CookiePath;
  473. protection = authConfig.Protection;
  474. #if NET_1_1
  475. requireSSL = authConfig.RequireSSL;
  476. slidingExpiration = authConfig.SlidingExpiration;
  477. #endif
  478. } else {
  479. cookieName = ".MONOAUTH";
  480. timeout = 30;
  481. cookiePath = "/";
  482. protection = FormsProtectionEnum.All;
  483. #if NET_1_1
  484. slidingExpiration = true;
  485. #endif
  486. }
  487. #endif
  488. // IV is 8 bytes long for 3DES
  489. init_vector = new byte [8];
  490. int len = cookieName.Length;
  491. for (int i = 0; i < 8; i++) {
  492. if (i >= len)
  493. break;
  494. init_vector [i] = (byte) cookieName [i];
  495. }
  496. initialized = true;
  497. }
  498. }
  499. #if NET_2_0
  500. static string MapUrl (string url) {
  501. if (UrlUtils.IsRelativeUrl (url))
  502. return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
  503. else
  504. return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
  505. }
  506. #endif
  507. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  508. {
  509. RedirectFromLoginPage (userName, createPersistentCookie, null);
  510. }
  511. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  512. {
  513. if (userName == null)
  514. return;
  515. Initialize ();
  516. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  517. Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  518. }
  519. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  520. {
  521. if (tOld == null)
  522. return null;
  523. DateTime now = DateTime.Now;
  524. TimeSpan toIssue = now - tOld.IssueDate;
  525. TimeSpan toExpiration = tOld.Expiration - now;
  526. if (toExpiration > toIssue)
  527. return tOld;
  528. FormsAuthenticationTicket tNew = tOld.Clone ();
  529. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  530. return tNew;
  531. }
  532. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  533. {
  534. Initialize ();
  535. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  536. }
  537. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  538. {
  539. HttpContext context = HttpContext.Current;
  540. if (context == null)
  541. throw new HttpException ("Context is null!");
  542. HttpResponse response = context.Response;
  543. if (response == null)
  544. throw new HttpException ("Response is null!");
  545. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  546. }
  547. public static void SignOut ()
  548. {
  549. Initialize ();
  550. HttpContext context = HttpContext.Current;
  551. if (context == null)
  552. throw new HttpException ("Context is null!");
  553. HttpResponse response = context.Response;
  554. if (response == null)
  555. throw new HttpException ("Response is null!");
  556. HttpCookieCollection cc = response.Cookies;
  557. cc.Remove (cookieName);
  558. HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
  559. expiration_cookie.Expires = new DateTime (1999, 10, 12);
  560. expiration_cookie.Path = cookiePath;
  561. cc.Add (expiration_cookie);
  562. #if NET_2_0
  563. Roles.DeleteCookie ();
  564. #endif
  565. }
  566. public static string FormsCookieName
  567. {
  568. get {
  569. Initialize ();
  570. return cookieName;
  571. }
  572. }
  573. public static string FormsCookiePath
  574. {
  575. get {
  576. Initialize ();
  577. return cookiePath;
  578. }
  579. }
  580. #if NET_1_1
  581. public static bool RequireSSL {
  582. get {
  583. Initialize ();
  584. return requireSSL;
  585. }
  586. }
  587. public static bool SlidingExpiration {
  588. get {
  589. Initialize ();
  590. return slidingExpiration;
  591. }
  592. }
  593. #endif
  594. #if NET_2_0
  595. public static string CookieDomain {
  596. get { Initialize (); return cookie_domain; }
  597. }
  598. public static HttpCookieMode CookieMode {
  599. get { Initialize (); return cookie_mode; }
  600. }
  601. public static bool CookiesSupported {
  602. get { Initialize (); return cookies_supported; }
  603. }
  604. public static string DefaultUrl {
  605. get { Initialize (); return default_url; }
  606. }
  607. public static bool EnableCrossAppRedirects {
  608. get { Initialize (); return enable_crossapp_redirects; }
  609. }
  610. public static string LoginUrl {
  611. get { Initialize (); return login_url; }
  612. }
  613. public static void RedirectToLoginPage ()
  614. {
  615. Redirect (LoginUrl);
  616. }
  617. [MonoTODO ("needs more tests")]
  618. public static void RedirectToLoginPage (string extraQueryString)
  619. {
  620. // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
  621. Redirect (LoginUrl + "?" + extraQueryString);
  622. }
  623. private static void Redirect (string url)
  624. {
  625. HttpContext.Current.Response.Redirect (url);
  626. }
  627. #endif
  628. private static void Redirect (string url, bool end)
  629. {
  630. HttpContext.Current.Response.Redirect (url, end);
  631. }
  632. }
  633. }