FormsAuthentication.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. static string authConfigPath = "system.web/authentication";
  46. static string machineKeyConfigPath = "system.web/machineKey";
  47. #if TARGET_J2EE
  48. const string Forms_initialized = "Forms.initialized";
  49. const string Forms_cookieName = "Forms.cookieName";
  50. const string Forms_cookiePath = "Forms.cookiePath";
  51. const string Forms_timeout = "Forms.timeout";
  52. const string Forms_protection = "Forms.protection";
  53. static bool initialized
  54. {
  55. get {
  56. object o = AppDomain.CurrentDomain.GetData (Forms_initialized);
  57. return o != null ? (bool) o : false;
  58. }
  59. set { AppDomain.CurrentDomain.SetData (Forms_initialized, value); }
  60. }
  61. static string cookieName
  62. {
  63. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookieName); }
  64. set { AppDomain.CurrentDomain.SetData (Forms_cookieName, value); }
  65. }
  66. static string cookiePath
  67. {
  68. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookiePath); }
  69. set { AppDomain.CurrentDomain.SetData (Forms_cookiePath, value); }
  70. }
  71. static int timeout
  72. {
  73. get {
  74. object o = AppDomain.CurrentDomain.GetData (Forms_timeout);
  75. return o != null ? (int) o : 0;
  76. }
  77. set { AppDomain.CurrentDomain.SetData (Forms_timeout, value); }
  78. }
  79. static FormsProtectionEnum protection
  80. {
  81. get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
  82. set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
  83. }
  84. static object locker = new object ();
  85. #else
  86. static bool initialized;
  87. static string cookieName;
  88. static string cookiePath;
  89. static int timeout;
  90. static FormsProtectionEnum protection;
  91. static object locker = new object ();
  92. #endif
  93. #if NET_1_1
  94. #if TARGET_J2EE
  95. const string Forms_requireSSL = "Forms.requireSSL";
  96. const string Forms_slidingExpiration = "Forms.slidingExpiration";
  97. static bool requireSSL
  98. {
  99. get {
  100. object o = AppDomain.CurrentDomain.GetData (Forms_requireSSL);
  101. return o != null ? (bool) o : false;
  102. }
  103. set { AppDomain.CurrentDomain.SetData (Forms_requireSSL, value); }
  104. }
  105. static bool slidingExpiration
  106. {
  107. get {
  108. object o = AppDomain.CurrentDomain.GetData (Forms_slidingExpiration);
  109. return o != null ? (bool) o : false;
  110. }
  111. set { AppDomain.CurrentDomain.SetData (Forms_slidingExpiration, value); }
  112. }
  113. #else
  114. static bool requireSSL;
  115. static bool slidingExpiration;
  116. #endif
  117. #endif
  118. #if NET_2_0
  119. #if TARGET_J2EE
  120. const string Forms_cookie_domain = "Forms.cookie_domain";
  121. const string Forms_cookie_mode = "Forms.cookie_mode";
  122. const string Forms_cookies_supported = "Forms.cookies_supported";
  123. const string Forms_default_url = "Forms.default_url";
  124. const string Forms_enable_crossapp_redirects = "Forms.enable_crossapp_redirects";
  125. const string Forms_login_url = "Forms.login_url";
  126. static string cookie_domain
  127. {
  128. get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookie_domain); }
  129. set { AppDomain.CurrentDomain.SetData (Forms_cookie_domain, value); }
  130. }
  131. static HttpCookieMode cookie_mode
  132. {
  133. get { return (HttpCookieMode) AppDomain.CurrentDomain.GetData (Forms_cookie_mode); }
  134. set { AppDomain.CurrentDomain.SetData (Forms_cookie_mode, value); }
  135. }
  136. static bool cookies_supported
  137. {
  138. get {
  139. object o = AppDomain.CurrentDomain.GetData (Forms_cookies_supported);
  140. return o != null ? (bool) o : false;
  141. }
  142. set { AppDomain.CurrentDomain.SetData (Forms_cookies_supported, value); }
  143. }
  144. static string default_url
  145. {
  146. get { return (string) AppDomain.CurrentDomain.GetData (Forms_default_url); }
  147. set { AppDomain.CurrentDomain.SetData (Forms_default_url, value); }
  148. }
  149. static bool enable_crossapp_redirects
  150. {
  151. get {
  152. object o = AppDomain.CurrentDomain.GetData (Forms_enable_crossapp_redirects);
  153. return o != null ? (bool) o : false;
  154. }
  155. set { AppDomain.CurrentDomain.SetData (Forms_enable_crossapp_redirects, value); }
  156. }
  157. static string login_url
  158. {
  159. get { return (string) AppDomain.CurrentDomain.GetData (Forms_login_url); }
  160. set { AppDomain.CurrentDomain.SetData (Forms_login_url, value); }
  161. }
  162. #else
  163. static string cookie_domain;
  164. static HttpCookieMode cookie_mode;
  165. static bool cookies_supported;
  166. static string default_url;
  167. static bool enable_crossapp_redirects;
  168. static string login_url;
  169. #endif
  170. #endif
  171. // same names and order used in xsp
  172. static string [] indexFiles = { "index.aspx",
  173. "Default.aspx",
  174. "default.aspx",
  175. "index.html",
  176. "index.htm" };
  177. public FormsAuthentication ()
  178. {
  179. }
  180. public static bool Authenticate (string name, string password)
  181. {
  182. if (name == null || password == null)
  183. return false;
  184. Initialize ();
  185. HttpContext context = HttpContext.Current;
  186. if (context == null)
  187. throw new HttpException ("Context is null!");
  188. name = name.ToLower (Helpers.InvariantCulture);
  189. #if NET_2_0
  190. AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
  191. FormsAuthenticationCredentials config = section.Forms.Credentials;
  192. FormsAuthenticationUser user = config.Users[name];
  193. string stored = null;
  194. if (user != null)
  195. stored = user.Password;
  196. #else
  197. AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
  198. Hashtable users = config.CredentialUsers;
  199. string stored = users [name] as string;
  200. #endif
  201. if (stored == null)
  202. return false;
  203. bool caseInsensitive = true;
  204. switch (config.PasswordFormat) {
  205. case FormsAuthPasswordFormat.Clear:
  206. caseInsensitive = false;
  207. /* Do nothing */
  208. break;
  209. case FormsAuthPasswordFormat.MD5:
  210. password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
  211. break;
  212. case FormsAuthPasswordFormat.SHA1:
  213. password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
  214. break;
  215. }
  216. return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
  217. }
  218. static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
  219. {
  220. if (protection == FormsProtectionEnum.None)
  221. return FormsAuthenticationTicket.FromByteArray (bytes);
  222. #if NET_2_0
  223. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  224. #else
  225. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  226. #endif
  227. byte [] result = null;
  228. if (protection == FormsProtectionEnum.All) {
  229. result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
  230. } else if (protection == FormsProtectionEnum.Encryption) {
  231. result = MachineKeySectionUtils.Decrypt (config, bytes);
  232. } else if (protection == FormsProtectionEnum.Validation) {
  233. result = MachineKeySectionUtils.Verify (config, bytes);
  234. }
  235. return FormsAuthenticationTicket.FromByteArray (result);
  236. }
  237. public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
  238. {
  239. if (encryptedTicket == null || encryptedTicket == String.Empty)
  240. throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
  241. Initialize ();
  242. FormsAuthenticationTicket ticket;
  243. byte [] bytes = Convert.FromBase64String (encryptedTicket);
  244. try {
  245. ticket = Decrypt2 (bytes);
  246. } catch (Exception) {
  247. ticket = null;
  248. }
  249. return ticket;
  250. }
  251. public static string Encrypt (FormsAuthenticationTicket ticket)
  252. {
  253. if (ticket == null)
  254. throw new ArgumentNullException ("ticket");
  255. Initialize ();
  256. byte [] ticket_bytes = ticket.ToByteArray ();
  257. if (protection == FormsProtectionEnum.None)
  258. return Convert.ToBase64String (ticket_bytes);
  259. byte [] result = null;
  260. #if NET_2_0
  261. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
  262. #else
  263. MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
  264. #endif
  265. if (protection == FormsProtectionEnum.All) {
  266. result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
  267. } else if (protection == FormsProtectionEnum.Encryption) {
  268. result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
  269. } else if (protection == FormsProtectionEnum.Validation) {
  270. result = MachineKeySectionUtils.Sign (config, ticket_bytes);
  271. }
  272. return Convert.ToBase64String (result);
  273. }
  274. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
  275. {
  276. return GetAuthCookie (userName, createPersistentCookie, null);
  277. }
  278. public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  279. {
  280. Initialize ();
  281. if (userName == null)
  282. userName = String.Empty;
  283. if (strCookiePath == null || strCookiePath.Length == 0)
  284. strCookiePath = cookiePath;
  285. DateTime now = DateTime.Now;
  286. DateTime then;
  287. if (createPersistentCookie)
  288. then = now.AddYears (50);
  289. else
  290. then = now.AddMinutes (timeout);
  291. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
  292. userName,
  293. now,
  294. then,
  295. createPersistentCookie,
  296. String.Empty,
  297. cookiePath);
  298. if (!createPersistentCookie)
  299. then = DateTime.MinValue;
  300. HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
  301. if (requireSSL)
  302. cookie.Secure = true;
  303. #if NET_2_0
  304. if (!String.IsNullOrEmpty (cookie_domain))
  305. cookie.Domain = cookie_domain;
  306. #endif
  307. return cookie;
  308. }
  309. internal static string ReturnUrl
  310. {
  311. get { return HttpContext.Current.Request ["RETURNURL"]; }
  312. }
  313. public static string GetRedirectUrl (string userName, bool createPersistentCookie)
  314. {
  315. if (userName == null)
  316. return null;
  317. Initialize ();
  318. HttpRequest request = HttpContext.Current.Request;
  319. string returnUrl = ReturnUrl;
  320. if (returnUrl != null)
  321. return returnUrl;
  322. returnUrl = request.ApplicationPath;
  323. string apppath = request.PhysicalApplicationPath;
  324. bool found = false;
  325. foreach (string indexFile in indexFiles) {
  326. string filePath = Path.Combine (apppath, indexFile);
  327. if (File.Exists (filePath)) {
  328. returnUrl = UrlUtils.Combine (returnUrl, indexFile);
  329. found = true;
  330. break;
  331. }
  332. }
  333. if (!found)
  334. returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
  335. return returnUrl;
  336. }
  337. static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
  338. {
  339. if (password == null)
  340. throw new ArgumentNullException ("password");
  341. byte [] bytes;
  342. switch (passwordFormat) {
  343. case FormsAuthPasswordFormat.MD5:
  344. bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  345. break;
  346. case FormsAuthPasswordFormat.SHA1:
  347. bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
  348. break;
  349. default:
  350. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  351. }
  352. return MachineKeySectionUtils.GetHexString (bytes);
  353. }
  354. public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
  355. {
  356. if (password == null)
  357. throw new ArgumentNullException ("password");
  358. if (passwordFormat == null)
  359. throw new ArgumentNullException ("passwordFormat");
  360. if (String.Compare (passwordFormat, "MD5", true, Helpers.InvariantCulture) == 0) {
  361. return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
  362. } else if (String.Compare (passwordFormat, "SHA1", true, Helpers.InvariantCulture) == 0) {
  363. return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
  364. } else {
  365. throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
  366. }
  367. }
  368. public static void Initialize ()
  369. {
  370. if (initialized)
  371. return;
  372. lock (locker) {
  373. if (initialized)
  374. return;
  375. #if NET_2_0
  376. AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
  377. FormsAuthenticationConfiguration config = section.Forms;
  378. cookieName = config.Name;
  379. timeout = (int)config.Timeout.TotalMinutes;
  380. cookiePath = config.Path;
  381. protection = config.Protection;
  382. requireSSL = config.RequireSSL;
  383. slidingExpiration = config.SlidingExpiration;
  384. cookie_domain = config.Domain;
  385. cookie_mode = config.Cookieless;
  386. cookies_supported = true; /* XXX ? */
  387. default_url = MapUrl(config.DefaultUrl);
  388. enable_crossapp_redirects = config.EnableCrossAppRedirects;
  389. login_url = MapUrl(config.LoginUrl);
  390. #else
  391. HttpContext context = HttpContext.Current;
  392. AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
  393. if (authConfig != null) {
  394. cookieName = authConfig.CookieName;
  395. timeout = authConfig.Timeout;
  396. cookiePath = authConfig.CookiePath;
  397. protection = authConfig.Protection;
  398. #if NET_1_1
  399. requireSSL = authConfig.RequireSSL;
  400. slidingExpiration = authConfig.SlidingExpiration;
  401. #endif
  402. } else {
  403. cookieName = ".MONOAUTH";
  404. timeout = 30;
  405. cookiePath = "/";
  406. protection = FormsProtectionEnum.All;
  407. #if NET_1_1
  408. slidingExpiration = true;
  409. #endif
  410. }
  411. #endif
  412. initialized = true;
  413. }
  414. }
  415. #if NET_2_0
  416. static string MapUrl (string url) {
  417. if (UrlUtils.IsRelativeUrl (url))
  418. return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
  419. else
  420. return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
  421. }
  422. #endif
  423. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
  424. {
  425. RedirectFromLoginPage (userName, createPersistentCookie, null);
  426. }
  427. public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
  428. {
  429. if (userName == null)
  430. return;
  431. Initialize ();
  432. SetAuthCookie (userName, createPersistentCookie, strCookiePath);
  433. Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
  434. }
  435. public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
  436. {
  437. if (tOld == null)
  438. return null;
  439. DateTime now = DateTime.Now;
  440. TimeSpan toIssue = now - tOld.IssueDate;
  441. TimeSpan toExpiration = tOld.Expiration - now;
  442. if (toExpiration > toIssue)
  443. return tOld;
  444. FormsAuthenticationTicket tNew = tOld.Clone ();
  445. tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
  446. return tNew;
  447. }
  448. public static void SetAuthCookie (string userName, bool createPersistentCookie)
  449. {
  450. Initialize ();
  451. SetAuthCookie (userName, createPersistentCookie, cookiePath);
  452. }
  453. public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
  454. {
  455. HttpContext context = HttpContext.Current;
  456. if (context == null)
  457. throw new HttpException ("Context is null!");
  458. HttpResponse response = context.Response;
  459. if (response == null)
  460. throw new HttpException ("Response is null!");
  461. response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
  462. }
  463. public static void SignOut ()
  464. {
  465. Initialize ();
  466. HttpContext context = HttpContext.Current;
  467. if (context == null)
  468. throw new HttpException ("Context is null!");
  469. HttpResponse response = context.Response;
  470. if (response == null)
  471. throw new HttpException ("Response is null!");
  472. HttpCookieCollection cc = response.Cookies;
  473. cc.Remove (cookieName);
  474. HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
  475. expiration_cookie.Expires = new DateTime (1999, 10, 12);
  476. expiration_cookie.Path = cookiePath;
  477. #if NET_2_0
  478. if (!String.IsNullOrEmpty (cookie_domain))
  479. expiration_cookie.Domain = cookie_domain;
  480. #endif
  481. cc.Add (expiration_cookie);
  482. #if NET_2_0
  483. Roles.DeleteCookie ();
  484. #endif
  485. }
  486. public static string FormsCookieName
  487. {
  488. get {
  489. Initialize ();
  490. return cookieName;
  491. }
  492. }
  493. public static string FormsCookiePath
  494. {
  495. get {
  496. Initialize ();
  497. return cookiePath;
  498. }
  499. }
  500. #if NET_1_1
  501. public static bool RequireSSL {
  502. get {
  503. Initialize ();
  504. return requireSSL;
  505. }
  506. }
  507. public static bool SlidingExpiration {
  508. get {
  509. Initialize ();
  510. return slidingExpiration;
  511. }
  512. }
  513. #endif
  514. #if NET_2_0
  515. public static string CookieDomain {
  516. get { Initialize (); return cookie_domain; }
  517. }
  518. public static HttpCookieMode CookieMode {
  519. get { Initialize (); return cookie_mode; }
  520. }
  521. public static bool CookiesSupported {
  522. get { Initialize (); return cookies_supported; }
  523. }
  524. public static string DefaultUrl {
  525. get { Initialize (); return default_url; }
  526. }
  527. public static bool EnableCrossAppRedirects {
  528. get { Initialize (); return enable_crossapp_redirects; }
  529. }
  530. public static string LoginUrl {
  531. get { Initialize (); return login_url; }
  532. }
  533. public static void RedirectToLoginPage ()
  534. {
  535. Redirect (LoginUrl);
  536. }
  537. [MonoTODO ("needs more tests")]
  538. public static void RedirectToLoginPage (string extraQueryString)
  539. {
  540. // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
  541. Redirect (LoginUrl + "?" + extraQueryString);
  542. }
  543. static void Redirect (string url)
  544. {
  545. HttpContext.Current.Response.Redirect (url);
  546. }
  547. #endif
  548. static void Redirect (string url, bool end)
  549. {
  550. HttpContext.Current.Response.Redirect (url, end);
  551. }
  552. }
  553. }