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 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.Util;
41 namespace System.Web.Security
43 // CAS - no InheritanceDemand here as the class is sealed
44 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45 public sealed class FormsAuthentication
47 const int MD5_hash_size = 16;
48 const int SHA1_hash_size = 20;
50 static string authConfigPath = "system.web/authentication";
51 static string machineKeyConfigPath = "system.web/machineKey";
52 static bool initialized;
53 static string cookieName;
54 static string cookiePath;
56 static FormsProtectionEnum protection;
57 static object locker = new object ();
58 static byte [] init_vector; // initialization vector used for 3DES
60 static bool requireSSL;
61 static bool slidingExpiration;
64 static string cookie_domain;
65 static HttpCookieMode cookie_mode;
66 static bool cookies_supported;
67 static string default_url;
68 static bool enable_crossapp_redirects;
69 static string login_url;
71 // same names and order used in xsp
72 static string [] indexFiles = { "index.aspx",
78 public FormsAuthentication ()
82 public static bool Authenticate (string name, string password)
84 if (name == null || password == null)
88 HttpContext context = HttpContext.Current;
90 throw new HttpException ("Context is null!");
93 AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
94 FormsAuthenticationCredentials config = section.Forms.Credentials;
95 FormsAuthenticationUser user = config.Users[name];
99 stored = user.Password;
101 AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
102 Hashtable users = config.CredentialUsers;
103 string stored = users [name] as string;
108 switch (config.PasswordFormat) {
109 case FormsAuthPasswordFormat.Clear:
112 case FormsAuthPasswordFormat.MD5:
113 password = HashPasswordForStoringInConfigFile (password, "MD5");
115 case FormsAuthPasswordFormat.SHA1:
116 password = HashPasswordForStoringInConfigFile (password, "SHA1");
120 return (password == stored);
123 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
125 if (protection == FormsProtectionEnum.None)
126 return FormsAuthenticationTicket.FromByteArray (bytes);
129 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
131 MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
133 bool all = (protection == FormsProtectionEnum.All);
135 byte [] result = bytes;
136 if (all || protection == FormsProtectionEnum.Encryption) {
137 ICryptoTransform decryptor;
138 decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
139 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
143 if (all || protection == FormsProtectionEnum.Validation) {
145 MachineKeyValidation validationType;
148 validationType = config.Validation;
150 validationType = config.ValidationType;
152 if (validationType == MachineKeyValidation.MD5)
153 count = MD5_hash_size;
155 count = SHA1_hash_size; // 3DES and SHA1
158 byte [] vk = config.ValidationKeyBytes;
160 byte [] vk = config.ValidationKey;
162 byte [] mix = new byte [result.Length - count + vk.Length];
163 Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
164 Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
167 switch (validationType) {
168 case MachineKeyValidation.MD5:
169 hash = MD5.Create ().ComputeHash (mix);
171 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
172 case MachineKeyValidation.TripleDES:
173 case MachineKeyValidation.SHA1:
174 hash = SHA1.Create ().ComputeHash (mix);
178 if (result.Length < count)
179 throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
182 for (i = result.Length - count, k = 0; k < count; i++, k++) {
183 if (result [i] != hash [k])
184 throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
188 return FormsAuthenticationTicket.FromByteArray (result);
191 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
193 if (encryptedTicket == null || encryptedTicket == String.Empty)
194 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
198 FormsAuthenticationTicket ticket;
200 byte [] bytes = MachineKeySection.GetBytes (encryptedTicket, encryptedTicket.Length);
202 byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
205 ticket = Decrypt2 (bytes);
206 } catch (Exception) {
213 public static string Encrypt (FormsAuthenticationTicket ticket)
216 throw new ArgumentNullException ("ticket");
219 byte [] ticket_bytes = ticket.ToByteArray ();
220 if (protection == FormsProtectionEnum.None)
221 return GetHexString (ticket_bytes);
223 byte [] result = ticket_bytes;
225 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
227 MachineKeyConfig config = HttpContext.GetAppConfig (machineKeyConfigPath) as MachineKeyConfig;
229 bool all = (protection == FormsProtectionEnum.All);
230 if (all || protection == FormsProtectionEnum.Validation) {
231 byte [] valid_bytes = null;
233 byte [] vk = config.ValidationKeyBytes;
235 byte [] vk = config.ValidationKey;
237 byte [] mix = new byte [ticket_bytes.Length + vk.Length];
238 Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
239 Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
245 config.ValidationType
248 case MachineKeyValidation.MD5:
249 valid_bytes = MD5.Create ().ComputeHash (mix);
251 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
252 case MachineKeyValidation.TripleDES:
253 case MachineKeyValidation.SHA1:
254 valid_bytes = SHA1.Create ().ComputeHash (mix);
258 int tlen = ticket_bytes.Length;
259 int vlen = valid_bytes.Length;
260 result = new byte [tlen + vlen];
261 Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
262 Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
265 if (all || protection == FormsProtectionEnum.Encryption) {
266 ICryptoTransform encryptor;
267 encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
268 result = encryptor.TransformFinalBlock (result, 0, result.Length);
271 return GetHexString (result);
274 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
276 return GetAuthCookie (userName, createPersistentCookie, null);
279 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
283 if (userName == null)
284 userName = String.Empty;
286 if (strCookiePath == null || strCookiePath.Length == 0)
287 strCookiePath = cookiePath;
289 DateTime now = DateTime.Now;
291 if (createPersistentCookie)
292 then = now.AddYears (50);
294 then = now.AddMinutes (timeout);
296 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
300 createPersistentCookie,
304 if (!createPersistentCookie)
305 then = DateTime.MinValue;
307 HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
309 cookie.Secure = true;
313 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
315 if (userName == null)
319 HttpRequest request = HttpContext.Current.Request;
320 string returnUrl = request ["RETURNURL"];
321 if (returnUrl != null)
324 returnUrl = request.ApplicationPath;
325 string apppath = request.PhysicalApplicationPath;
328 foreach (string indexFile in indexFiles) {
329 string filePath = Path.Combine (apppath, indexFile);
330 if (File.Exists (filePath)) {
331 returnUrl = UrlUtils.Combine (returnUrl, indexFile);
338 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
343 static string GetHexString (byte [] bytes)
345 StringBuilder result = new StringBuilder (bytes.Length * 2);
346 foreach (byte b in bytes)
347 result.AppendFormat ("{0:X2}", (int) b);
349 return result.ToString ();
352 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
354 if (password == null)
355 throw new ArgumentNullException ("password");
357 if (passwordFormat == null)
358 throw new ArgumentNullException ("passwordFormat");
361 if (String.Compare (passwordFormat, "MD5", true) == 0) {
362 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
363 } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
364 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
366 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
369 return GetHexString (bytes);
372 public static void Initialize ()
382 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
383 FormsAuthenticationConfiguration config = section.Forms;
385 cookieName = config.Name;
386 timeout = (int)config.Timeout.TotalMinutes;
387 cookiePath = config.Path;
388 protection = config.Protection;
389 requireSSL = config.RequireSSL;
390 slidingExpiration = config.SlidingExpiration;
391 cookie_domain = config.Domain;
392 cookie_mode = config.Cookieless;
393 cookies_supported = true; /* XXX ? */
394 default_url = MapUrl(config.DefaultUrl);
395 enable_crossapp_redirects = config.EnableCrossAppRedirects;
396 login_url = MapUrl(config.LoginUrl);
398 HttpContext context = HttpContext.Current;
399 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
400 if (authConfig != null) {
401 cookieName = authConfig.CookieName;
402 timeout = authConfig.Timeout;
403 cookiePath = authConfig.CookiePath;
404 protection = authConfig.Protection;
406 requireSSL = authConfig.RequireSSL;
407 slidingExpiration = authConfig.SlidingExpiration;
410 cookieName = ".MONOAUTH";
413 protection = FormsProtectionEnum.All;
415 slidingExpiration = true;
420 // IV is 8 bytes long for 3DES
421 init_vector = new byte [8];
422 int len = cookieName.Length;
423 for (int i = 0; i < 8; i++) {
427 init_vector [i] = (byte) cookieName [i];
434 static string MapUrl (string url) {
435 if (UrlUtils.IsRelativeUrl (url))
436 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
438 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
441 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
443 RedirectFromLoginPage (userName, createPersistentCookie, null);
446 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
448 if (userName == null)
452 SetAuthCookie (userName, createPersistentCookie, strCookiePath);
453 Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
456 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
461 DateTime now = DateTime.Now;
462 TimeSpan toIssue = now - tOld.IssueDate;
463 TimeSpan toExpiration = tOld.Expiration - now;
464 if (toExpiration > toIssue)
467 FormsAuthenticationTicket tNew = tOld.Clone ();
468 tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
472 public static void SetAuthCookie (string userName, bool createPersistentCookie)
475 SetAuthCookie (userName, createPersistentCookie, cookiePath);
478 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
480 HttpContext context = HttpContext.Current;
482 throw new HttpException ("Context is null!");
484 HttpResponse response = context.Response;
485 if (response == null)
486 throw new HttpException ("Response is null!");
488 response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
491 public static void SignOut ()
495 HttpContext context = HttpContext.Current;
497 throw new HttpException ("Context is null!");
499 HttpResponse response = context.Response;
500 if (response == null)
501 throw new HttpException ("Response is null!");
503 HttpCookieCollection cc = response.Cookies;
504 cc.Remove (cookieName);
505 HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
506 expiration_cookie.Expires = new DateTime (1999, 10, 12);
507 expiration_cookie.Path = cookiePath;
508 cc.Add (expiration_cookie);
511 public static string FormsCookieName
519 public static string FormsCookiePath
527 public static bool RequireSSL {
534 public static bool SlidingExpiration {
537 return slidingExpiration;
543 public static string CookieDomain {
544 get { Initialize (); return cookie_domain; }
547 public static HttpCookieMode CookieMode {
548 get { Initialize (); return cookie_mode; }
551 public static bool CookiesSupported {
552 get { Initialize (); return cookies_supported; }
555 public static string DefaultUrl {
556 get { Initialize (); return default_url; }
559 public static bool EnableCrossAppRedirects {
560 get { Initialize (); return enable_crossapp_redirects; }
563 public static string LoginUrl {
564 get { Initialize (); return login_url; }
567 public static void RedirectToLoginPage ()
572 [MonoTODO ("needs more tests")]
573 public static void RedirectToLoginPage (string extraQueryString)
575 // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
576 Redirect (LoginUrl + "?" + extraQueryString);
579 private static void Redirect (string url)
581 HttpContext.Current.Response.Redirect (url);
584 private static void Redirect (string url, bool end)
586 HttpContext.Current.Response.Redirect (url, end);