2 // System.Web.Security.FormsAuthentication
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (c) 2005-2010 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
34 using System.Security.Cryptography;
35 using System.Security.Permissions;
38 using System.Web.Configuration;
39 using System.Web.Compilation;
40 using System.Web.Util;
41 using System.Globalization;
42 using System.Collections.Specialized;
44 namespace System.Web.Security
46 // CAS - no InheritanceDemand here as the class is sealed
47 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 public sealed class FormsAuthentication
50 static string authConfigPath = "system.web/authentication";
51 static string machineKeyConfigPath = "system.web/machineKey";
52 static object locker = new object ();
54 const string Forms_initialized = "Forms.initialized";
55 const string Forms_cookieName = "Forms.cookieName";
56 const string Forms_cookiePath = "Forms.cookiePath";
57 const string Forms_timeout = "Forms.timeout";
58 const string Forms_protection = "Forms.protection";
59 static bool initialized
62 object o = AppDomain.CurrentDomain.GetData (Forms_initialized);
63 return o != null ? (bool) o : false;
65 set { AppDomain.CurrentDomain.SetData (Forms_initialized, value); }
67 static string cookieName
69 get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookieName); }
70 set { AppDomain.CurrentDomain.SetData (Forms_cookieName, value); }
72 static string cookiePath
74 get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookiePath); }
75 set { AppDomain.CurrentDomain.SetData (Forms_cookiePath, value); }
80 object o = AppDomain.CurrentDomain.GetData (Forms_timeout);
81 return o != null ? (int) o : 0;
83 set { AppDomain.CurrentDomain.SetData (Forms_timeout, value); }
85 static FormsProtectionEnum protection
87 get { return (FormsProtectionEnum) AppDomain.CurrentDomain.GetData (Forms_protection); }
88 set { AppDomain.CurrentDomain.SetData (Forms_protection, value); }
91 const string Forms_requireSSL = "Forms.requireSSL";
92 const string Forms_slidingExpiration = "Forms.slidingExpiration";
94 static bool requireSSL
97 object o = AppDomain.CurrentDomain.GetData (Forms_requireSSL);
98 return o != null ? (bool) o : false;
100 set { AppDomain.CurrentDomain.SetData (Forms_requireSSL, value); }
102 static bool slidingExpiration
105 object o = AppDomain.CurrentDomain.GetData (Forms_slidingExpiration);
106 return o != null ? (bool) o : false;
108 set { AppDomain.CurrentDomain.SetData (Forms_slidingExpiration, value); }
111 const string Forms_cookie_domain = "Forms.cookie_domain";
112 const string Forms_cookie_mode = "Forms.cookie_mode";
113 const string Forms_cookies_supported = "Forms.cookies_supported";
114 const string Forms_default_url = "Forms.default_url";
115 const string Forms_enable_crossapp_redirects = "Forms.enable_crossapp_redirects";
116 const string Forms_login_url = "Forms.login_url";
117 static string cookie_domain
119 get { return (string) AppDomain.CurrentDomain.GetData (Forms_cookie_domain); }
120 set { AppDomain.CurrentDomain.SetData (Forms_cookie_domain, value); }
122 static HttpCookieMode cookie_mode
124 get { return (HttpCookieMode) AppDomain.CurrentDomain.GetData (Forms_cookie_mode); }
125 set { AppDomain.CurrentDomain.SetData (Forms_cookie_mode, value); }
127 static bool cookies_supported
130 object o = AppDomain.CurrentDomain.GetData (Forms_cookies_supported);
131 return o != null ? (bool) o : false;
133 set { AppDomain.CurrentDomain.SetData (Forms_cookies_supported, value); }
135 static string default_url
137 get { return (string) AppDomain.CurrentDomain.GetData (Forms_default_url); }
138 set { AppDomain.CurrentDomain.SetData (Forms_default_url, value); }
140 static bool enable_crossapp_redirects
143 object o = AppDomain.CurrentDomain.GetData (Forms_enable_crossapp_redirects);
144 return o != null ? (bool) o : false;
146 set { AppDomain.CurrentDomain.SetData (Forms_enable_crossapp_redirects, value); }
148 static string login_url
150 get { return (string) AppDomain.CurrentDomain.GetData (Forms_login_url); }
151 set { AppDomain.CurrentDomain.SetData (Forms_login_url, value); }
154 static bool initialized;
155 static string cookieName;
156 static string cookiePath;
158 static FormsProtectionEnum protection;
159 static bool requireSSL;
160 static bool slidingExpiration;
161 static string cookie_domain;
162 static HttpCookieMode cookie_mode;
163 static bool cookies_supported;
164 static string default_url;
165 static bool enable_crossapp_redirects;
166 static string login_url;
168 // same names and order used in xsp
169 static string [] indexFiles = { "index.aspx",
175 public static TimeSpan Timeout {
179 public static bool IsEnabled {
180 get { return initialized; }
183 public static void EnableFormsAuthentication (NameValueCollection configurationData)
185 BuildManager.AssertPreStartMethodsRunning ();
186 if (configurationData == null || configurationData.Count == 0)
189 string value = configurationData ["loginUrl"];
190 if (!String.IsNullOrEmpty (value))
193 value = configurationData ["defaultUrl"];
194 if (!String.IsNullOrEmpty (value))
198 public FormsAuthentication ()
202 public static bool Authenticate (string name, string password)
204 if (name == null || password == null)
208 HttpContext context = HttpContext.Current;
210 throw new HttpException ("Context is null!");
212 name = name.ToLower (Helpers.InvariantCulture);
214 AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
215 FormsAuthenticationCredentials config = section.Forms.Credentials;
216 FormsAuthenticationUser user = config.Users[name];
217 string stored = null;
220 stored = user.Password;
225 bool caseInsensitive = true;
226 switch (config.PasswordFormat) {
227 case FormsAuthPasswordFormat.Clear:
228 caseInsensitive = false;
231 case FormsAuthPasswordFormat.MD5:
232 password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
234 case FormsAuthPasswordFormat.SHA1:
235 password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
239 return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
242 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
244 if (protection == FormsProtectionEnum.None)
245 return FormsAuthenticationTicket.FromByteArray (bytes);
247 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
248 byte [] result = null;
249 if (protection == FormsProtectionEnum.All) {
250 result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
251 } else if (protection == FormsProtectionEnum.Encryption) {
252 result = MachineKeySectionUtils.Decrypt (config, bytes);
253 } else if (protection == FormsProtectionEnum.Validation) {
254 result = MachineKeySectionUtils.Verify (config, bytes);
257 return FormsAuthenticationTicket.FromByteArray (result);
260 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
262 if (String.IsNullOrEmpty (encryptedTicket))
263 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
267 FormsAuthenticationTicket ticket;
268 byte [] bytes = Convert.FromBase64String (encryptedTicket);
271 ticket = Decrypt2 (bytes);
272 } catch (Exception) {
279 public static string Encrypt (FormsAuthenticationTicket ticket)
282 throw new ArgumentNullException ("ticket");
285 byte [] ticket_bytes = ticket.ToByteArray ();
286 if (protection == FormsProtectionEnum.None)
287 return Convert.ToBase64String (ticket_bytes);
289 byte [] result = null;
290 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
292 if (protection == FormsProtectionEnum.All) {
293 result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
294 } else if (protection == FormsProtectionEnum.Encryption) {
295 result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
296 } else if (protection == FormsProtectionEnum.Validation) {
297 result = MachineKeySectionUtils.Sign (config, ticket_bytes);
300 return Convert.ToBase64String (result);
303 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
305 return GetAuthCookie (userName, createPersistentCookie, null);
308 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
312 if (userName == null)
313 userName = String.Empty;
315 if (strCookiePath == null || strCookiePath.Length == 0)
316 strCookiePath = cookiePath;
318 DateTime now = DateTime.Now;
320 if (createPersistentCookie)
321 then = now.AddYears (50);
323 then = now.AddMinutes (timeout);
325 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
329 createPersistentCookie,
333 if (!createPersistentCookie)
334 then = DateTime.MinValue;
336 HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
338 cookie.Secure = true;
339 if (!String.IsNullOrEmpty (cookie_domain))
340 cookie.Domain = cookie_domain;
345 internal static string ReturnUrl {
346 get { return HttpContext.Current.Request ["RETURNURL"]; }
349 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
351 if (userName == null)
355 HttpRequest request = HttpContext.Current.Request;
356 string returnUrl = ReturnUrl;
357 if (returnUrl != null)
360 returnUrl = request.ApplicationPath;
361 string apppath = request.PhysicalApplicationPath;
364 foreach (string indexFile in indexFiles) {
365 string filePath = Path.Combine (apppath, indexFile);
366 if (File.Exists (filePath)) {
367 returnUrl = UrlUtils.Combine (returnUrl, indexFile);
374 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
379 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
381 if (password == null)
382 throw new ArgumentNullException ("password");
385 switch (passwordFormat) {
386 case FormsAuthPasswordFormat.MD5:
387 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
390 case FormsAuthPasswordFormat.SHA1:
391 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
395 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
398 return MachineKeySectionUtils.GetHexString (bytes);
401 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
403 if (password == null)
404 throw new ArgumentNullException ("password");
406 if (passwordFormat == null)
407 throw new ArgumentNullException ("passwordFormat");
409 if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
410 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
411 } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
412 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
414 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
418 public static void Initialize ()
427 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
428 FormsAuthenticationConfiguration config = section.Forms;
430 cookieName = config.Name;
432 Timeout = config.Timeout;
434 timeout = (int)config.Timeout.TotalMinutes;
435 cookiePath = config.Path;
436 protection = config.Protection;
437 requireSSL = config.RequireSSL;
438 slidingExpiration = config.SlidingExpiration;
439 cookie_domain = config.Domain;
440 cookie_mode = config.Cookieless;
441 cookies_supported = true; /* XXX ? */
443 if (!String.IsNullOrEmpty (default_url))
444 default_url = MapUrl (default_url);
447 default_url = MapUrl(config.DefaultUrl);
448 enable_crossapp_redirects = config.EnableCrossAppRedirects;
450 if (!String.IsNullOrEmpty (login_url))
451 login_url = MapUrl (login_url);
454 login_url = MapUrl(config.LoginUrl);
460 static string MapUrl (string url) {
461 if (UrlUtils.IsRelativeUrl (url))
462 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
464 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
467 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
469 RedirectFromLoginPage (userName, createPersistentCookie, null);
472 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
474 if (userName == null)
478 SetAuthCookie (userName, createPersistentCookie, strCookiePath);
479 Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
482 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
487 DateTime now = DateTime.Now;
488 TimeSpan toIssue = now - tOld.IssueDate;
489 TimeSpan toExpiration = tOld.Expiration - now;
490 if (toExpiration > toIssue)
493 FormsAuthenticationTicket tNew = tOld.Clone ();
494 tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
498 public static void SetAuthCookie (string userName, bool createPersistentCookie)
501 SetAuthCookie (userName, createPersistentCookie, cookiePath);
504 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
506 HttpContext context = HttpContext.Current;
508 throw new HttpException ("Context is null!");
510 HttpResponse response = context.Response;
511 if (response == null)
512 throw new HttpException ("Response is null!");
514 response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
517 public static void SignOut ()
521 HttpContext context = HttpContext.Current;
523 throw new HttpException ("Context is null!");
525 HttpResponse response = context.Response;
526 if (response == null)
527 throw new HttpException ("Response is null!");
529 HttpCookieCollection cc = response.Cookies;
530 cc.Remove (cookieName);
531 HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
532 expiration_cookie.Expires = new DateTime (1999, 10, 12);
533 expiration_cookie.Path = cookiePath;
534 if (!String.IsNullOrEmpty (cookie_domain))
535 expiration_cookie.Domain = cookie_domain;
536 cc.Add (expiration_cookie);
537 Roles.DeleteCookie ();
540 public static string FormsCookieName
548 public static string FormsCookiePath
556 public static bool RequireSSL {
563 public static bool SlidingExpiration {
566 return slidingExpiration;
570 public static string CookieDomain {
571 get { Initialize (); return cookie_domain; }
574 public static HttpCookieMode CookieMode {
575 get { Initialize (); return cookie_mode; }
578 public static bool CookiesSupported {
579 get { Initialize (); return cookies_supported; }
582 public static string DefaultUrl {
583 get { Initialize (); return default_url; }
586 public static bool EnableCrossAppRedirects {
587 get { Initialize (); return enable_crossapp_redirects; }
590 public static string LoginUrl {
591 get { Initialize (); return login_url; }
594 public static void RedirectToLoginPage ()
599 [MonoTODO ("needs more tests")]
600 public static void RedirectToLoginPage (string extraQueryString)
602 // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
603 Redirect (LoginUrl + "?" + extraQueryString);
606 static void Redirect (string url)
608 HttpContext.Current.Response.Redirect (url);
611 static void Redirect (string url, bool end)
613 HttpContext.Current.Response.Redirect (url, end);