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 bool initialized;
52 static string cookieName;
53 static string cookiePath;
55 static FormsProtectionEnum protection;
56 static object locker = new object ();
57 static byte [] init_vector; // initialization vector used for 3DES
59 static bool requireSSL;
60 static bool slidingExpiration;
63 static string cookie_domain;
64 static HttpCookieMode cookie_mode;
65 static bool cookies_supported;
66 static string default_url;
67 static bool enable_crossapp_redirects;
68 static string login_url;
70 // same names and order used in xsp
71 static string [] indexFiles = { "index.aspx",
80 public FormsAuthentication ()
84 public static bool Authenticate (string name, string password)
86 if (name == null || password == null)
90 HttpContext context = HttpContext.Current;
92 throw new HttpException ("Context is null!");
94 AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
95 Hashtable users = config.CredentialUsers;
96 string stored = users [name] as string;
100 switch (config.PasswordFormat) {
101 case FormsAuthPasswordFormat.Clear:
104 case FormsAuthPasswordFormat.MD5:
105 password = HashPasswordForStoringInConfigFile (password, "MD5");
107 case FormsAuthPasswordFormat.SHA1:
108 password = HashPasswordForStoringInConfigFile (password, "SHA1");
112 return (password == stored);
115 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
117 if (protection == FormsProtectionEnum.None)
118 return FormsAuthenticationTicket.FromByteArray (bytes);
120 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
121 bool all = (protection == FormsProtectionEnum.All);
123 byte [] result = bytes;
124 if (all || protection == FormsProtectionEnum.Encryption) {
125 ICryptoTransform decryptor;
126 decryptor = TripleDES.Create ().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
127 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
131 if (all || protection == FormsProtectionEnum.Validation) {
134 if (config.ValidationType == MachineKeyValidation.MD5)
135 count = MD5_hash_size;
137 count = SHA1_hash_size; // 3DES and SHA1
139 byte [] vk = config.ValidationKey;
140 byte [] mix = new byte [result.Length - count + vk.Length];
141 Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
142 Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
145 switch (config.ValidationType) {
146 case MachineKeyValidation.MD5:
147 hash = MD5.Create ().ComputeHash (mix);
149 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
150 case MachineKeyValidation.TripleDES:
151 case MachineKeyValidation.SHA1:
152 hash = SHA1.Create ().ComputeHash (mix);
156 if (result.Length < count)
157 throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
160 for (i = result.Length - count, k = 0; k < count; i++, k++) {
161 if (result [i] != hash [k])
162 throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
166 return FormsAuthenticationTicket.FromByteArray (result);
169 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
171 if (encryptedTicket == null || encryptedTicket == String.Empty)
172 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
176 FormsAuthenticationTicket ticket;
177 byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
179 ticket = Decrypt2 (bytes);
180 } catch (Exception) {
187 public static string Encrypt (FormsAuthenticationTicket ticket)
190 throw new ArgumentNullException ("ticket");
193 byte [] ticket_bytes = ticket.ToByteArray ();
194 if (protection == FormsProtectionEnum.None)
195 return GetHexString (ticket_bytes);
197 byte [] result = ticket_bytes;
198 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
199 bool all = (protection == FormsProtectionEnum.All);
200 if (all || protection == FormsProtectionEnum.Validation) {
201 byte [] valid_bytes = null;
202 byte [] vk = config.ValidationKey;
203 byte [] mix = new byte [ticket_bytes.Length + vk.Length];
204 Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
205 Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
207 switch (config.ValidationType) {
208 case MachineKeyValidation.MD5:
209 valid_bytes = MD5.Create ().ComputeHash (mix);
211 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
212 case MachineKeyValidation.TripleDES:
213 case MachineKeyValidation.SHA1:
214 valid_bytes = SHA1.Create ().ComputeHash (mix);
218 int tlen = ticket_bytes.Length;
219 int vlen = valid_bytes.Length;
220 result = new byte [tlen + vlen];
221 Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
222 Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
225 if (all || protection == FormsProtectionEnum.Encryption) {
226 ICryptoTransform encryptor;
227 encryptor = TripleDES.Create ().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
228 result = encryptor.TransformFinalBlock (result, 0, result.Length);
231 return GetHexString (result);
234 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
236 return GetAuthCookie (userName, createPersistentCookie, null);
239 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
243 if (userName == null)
244 userName = String.Empty;
246 if (strCookiePath == null || strCookiePath.Length == 0)
247 strCookiePath = cookiePath;
249 DateTime now = DateTime.Now;
251 if (createPersistentCookie)
252 then = now.AddYears (50);
254 then = now.AddMinutes (timeout);
256 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
260 createPersistentCookie,
264 if (!createPersistentCookie)
265 then = DateTime.MinValue;
267 return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
270 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
272 if (userName == null)
276 HttpRequest request = HttpContext.Current.Request;
277 string returnUrl = request ["RETURNURL"];
278 if (returnUrl != null)
281 returnUrl = request.ApplicationPath;
282 string apppath = request.PhysicalApplicationPath;
285 foreach (string indexFile in indexFiles) {
286 string filePath = Path.Combine (apppath, indexFile);
287 if (File.Exists (filePath)) {
288 returnUrl = UrlUtils.Combine (returnUrl, indexFile);
295 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
300 static string GetHexString (byte [] bytes)
302 StringBuilder result = new StringBuilder (bytes.Length * 2);
303 foreach (byte b in bytes)
304 result.AppendFormat ("{0:X2}", (int) b);
306 return result.ToString ();
309 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
311 if (password == null)
312 throw new ArgumentNullException ("password");
314 if (passwordFormat == null)
315 throw new ArgumentNullException ("passwordFormat");
318 if (String.Compare (passwordFormat, "MD5", true) == 0) {
319 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
320 } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
321 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
323 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
326 return GetHexString (bytes);
329 public static void Initialize ()
338 HttpContext context = HttpContext.Current;
340 AuthConfig authConfig = null;
342 authConfig = context.GetConfig (authConfigPath) as AuthConfig;
344 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
346 if (authConfig != null) {
347 cookieName = authConfig.CookieName;
348 timeout = authConfig.Timeout;
349 cookiePath = authConfig.CookiePath;
350 protection = authConfig.Protection;
352 requireSSL = authConfig.RequireSSL;
353 slidingExpiration = authConfig.SlidingExpiration;
356 cookie_domain = authConfig.CookieDomain;
357 cookie_mode = authConfig.CookieMode;
358 cookies_supported = authConfig.CookiesSupported;
359 default_url = authConfig.DefaultUrl;
360 enable_crossapp_redirects = authConfig.EnableCrossAppRedirects;
361 login_url = authConfig.LoginUrl;
364 cookieName = ".MONOAUTH";
367 protection = FormsProtectionEnum.All;
369 slidingExpiration = true;
372 cookie_domain = String.Empty;
373 cookie_mode = HttpCookieMode.UseDeviceProfile;
374 cookies_supported = true;
375 default_url = "/default.aspx";
376 login_url = "/login.aspx";
380 // IV is 8 bytes long for 3DES
381 init_vector = new byte [8];
382 int len = cookieName.Length;
383 for (int i = 0; i < 8; i++) {
387 init_vector [i] = (byte) cookieName [i];
394 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
396 RedirectFromLoginPage (userName, createPersistentCookie, null);
399 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
401 if (userName == null)
405 SetAuthCookie (userName, createPersistentCookie, strCookiePath);
406 Redirect (GetRedirectUrl (userName, createPersistentCookie));
409 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
414 DateTime now = DateTime.Now;
415 TimeSpan toIssue = now - tOld.IssueDate;
416 TimeSpan toExpiration = tOld.Expiration - now;
417 if (toExpiration > toIssue)
420 FormsAuthenticationTicket tNew = tOld.Clone ();
421 tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
425 public static void SetAuthCookie (string userName, bool createPersistentCookie)
428 SetAuthCookie (userName, createPersistentCookie, cookiePath);
431 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
433 HttpContext context = HttpContext.Current;
435 throw new HttpException ("Context is null!");
437 HttpResponse response = context.Response;
438 if (response == null)
439 throw new HttpException ("Response is null!");
441 response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
444 public static void SignOut ()
448 HttpContext context = HttpContext.Current;
450 throw new HttpException ("Context is null!");
452 HttpResponse response = context.Response;
453 if (response == null)
454 throw new HttpException ("Response is null!");
456 HttpCookieCollection cc = response.Cookies;
457 cc.Remove (cookieName);
458 HttpCookie expiration_cookie = new HttpCookie (cookieName, "");
459 expiration_cookie.Expires = new DateTime (1999, 10, 12);
460 expiration_cookie.Path = cookiePath;
461 cc.Add (expiration_cookie);
464 public static string FormsCookieName
472 public static string FormsCookiePath
480 public static bool RequireSSL {
487 public static bool SlidingExpiration {
490 return slidingExpiration;
496 public static string CookieDomain {
497 get { return cookie_domain; }
500 public static HttpCookieMode CookieMode {
501 get { return cookie_mode; }
504 public static bool CookiesSupported {
505 get { return cookies_supported; }
508 public static string DefaultUrl {
509 get { return default_url; }
512 public static bool EnableCrossAppRedirects {
513 get { return enable_crossapp_redirects; }
516 public static string LoginUrl {
517 get { return login_url; }
520 public static void RedirectToLoginPage ()
525 [MonoTODO ("needs more tests")]
526 public static void RedirectToLoginPage (string extraQueryString)
528 // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
529 Redirect (LoginUrl + "?" + extraQueryString);
532 private static void Redirect (string url)
534 HttpContext.Current.Response.Redirect (url);