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.
33 using System.Collections;
35 using System.Security.Cryptography;
38 using System.Web.Configuration;
39 using System.Web.Util;
41 namespace System.Web.Security
43 public sealed class FormsAuthentication
45 const int MD5_hash_size = 16;
46 const int SHA1_hash_size = 20;
48 static string authConfigPath = "system.web/authentication";
49 static bool initialized;
50 static string cookieName;
51 static string cookiePath;
53 static FormsProtectionEnum protection;
54 static object locker = new object ();
55 static byte [] init_vector; // initialization vector used for 3DES
57 static bool requireSSL;
58 static bool slidingExpiration;
61 // same names and order used in xsp
62 static string [] indexFiles = { "index.aspx",
68 public static bool Authenticate (string name, string password)
70 if (name == null || password == null)
74 HttpContext context = HttpContext.Current;
76 throw new HttpException ("Context is null!");
78 AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
79 Hashtable users = config.CredentialUsers;
80 string stored = users [name] as string;
84 switch (config.PasswordFormat) {
85 case FormsAuthPasswordFormat.Clear:
88 case FormsAuthPasswordFormat.MD5:
89 password = HashPasswordForStoringInConfigFile (password, "MD5");
91 case FormsAuthPasswordFormat.SHA1:
92 password = HashPasswordForStoringInConfigFile (password, "SHA1");
96 return (password == stored);
99 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
101 if (protection == FormsProtectionEnum.None)
102 return FormsAuthenticationTicket.FromByteArray (bytes);
104 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
105 bool all = (protection == FormsProtectionEnum.All);
107 byte [] result = bytes;
108 if (all || protection == FormsProtectionEnum.Encryption) {
109 ICryptoTransform decryptor;
110 decryptor = new TripleDESCryptoServiceProvider().CreateDecryptor (config.DecryptionKey192Bits, init_vector);
111 result = decryptor.TransformFinalBlock (bytes, 0, bytes.Length);
115 if (all || protection == FormsProtectionEnum.Validation) {
118 if (config.ValidationType == MachineKeyValidation.MD5)
119 count = MD5_hash_size;
121 count = SHA1_hash_size; // 3DES and SHA1
123 byte [] vk = config.ValidationKey;
124 byte [] mix = new byte [result.Length - count + vk.Length];
125 Buffer.BlockCopy (result, 0, mix, 0, result.Length - count);
126 Buffer.BlockCopy (vk, 0, mix, result.Length - count, vk.Length);
129 switch (config.ValidationType) {
130 case MachineKeyValidation.MD5:
131 hash = MD5.Create ().ComputeHash (mix);
133 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
134 case MachineKeyValidation.TripleDES:
135 case MachineKeyValidation.SHA1:
136 hash = SHA1.Create ().ComputeHash (mix);
140 if (result.Length < count)
141 throw new ArgumentException ("Error validating ticket (length).", "encryptedTicket");
144 for (i = result.Length - count, k = 0; k < count; i++, k++) {
145 if (result [i] != hash [k])
146 throw new ArgumentException ("Error validating ticket.", "encryptedTicket");
150 return FormsAuthenticationTicket.FromByteArray (result);
153 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
155 if (encryptedTicket == null || encryptedTicket == String.Empty)
156 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
160 FormsAuthenticationTicket ticket;
161 byte [] bytes = MachineKeyConfig.GetBytes (encryptedTicket, encryptedTicket.Length);
163 ticket = Decrypt2 (bytes);
164 } catch (Exception) {
171 public static string Encrypt (FormsAuthenticationTicket ticket)
174 throw new ArgumentNullException ("ticket");
177 byte [] ticket_bytes = ticket.ToByteArray ();
178 if (protection == FormsProtectionEnum.None)
179 return GetHexString (ticket_bytes);
181 byte [] result = ticket_bytes;
182 MachineKeyConfig config = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
183 bool all = (protection == FormsProtectionEnum.All);
184 if (all || protection == FormsProtectionEnum.Validation) {
185 byte [] valid_bytes = null;
186 byte [] vk = config.ValidationKey;
187 byte [] mix = new byte [ticket_bytes.Length + vk.Length];
188 Buffer.BlockCopy (ticket_bytes, 0, mix, 0, ticket_bytes.Length);
189 Buffer.BlockCopy (vk, 0, mix, result.Length, vk.Length);
191 switch (config.ValidationType) {
192 case MachineKeyValidation.MD5:
193 valid_bytes = MD5.Create ().ComputeHash (mix);
195 // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
196 case MachineKeyValidation.TripleDES:
197 case MachineKeyValidation.SHA1:
198 valid_bytes = SHA1.Create ().ComputeHash (mix);
202 int tlen = ticket_bytes.Length;
203 int vlen = valid_bytes.Length;
204 result = new byte [tlen + vlen];
205 Buffer.BlockCopy (ticket_bytes, 0, result, 0, tlen);
206 Buffer.BlockCopy (valid_bytes, 0, result, tlen, vlen);
209 if (all || protection == FormsProtectionEnum.Encryption) {
210 ICryptoTransform encryptor;
211 encryptor = new TripleDESCryptoServiceProvider().CreateEncryptor (config.DecryptionKey192Bits, init_vector);
212 result = encryptor.TransformFinalBlock (result, 0, result.Length);
215 return GetHexString (result);
218 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
220 return GetAuthCookie (userName, createPersistentCookie, null);
223 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
227 if (userName == null)
228 userName = String.Empty;
230 if (strCookiePath == null || strCookiePath.Length == 0)
231 strCookiePath = cookiePath;
233 DateTime now = DateTime.Now;
235 if (createPersistentCookie)
236 then = now.AddYears (50);
238 then = now.AddMinutes (timeout);
240 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
244 createPersistentCookie,
248 if (!createPersistentCookie)
249 then = DateTime.MinValue;
251 return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
254 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
256 if (userName == null)
260 HttpRequest request = HttpContext.Current.Request;
261 string returnUrl = request ["RETURNURL"];
262 if (returnUrl != null)
265 returnUrl = request.ApplicationPath;
266 string apppath = request.PhysicalApplicationPath;
269 foreach (string indexFile in indexFiles) {
270 string filePath = Path.Combine (apppath, indexFile);
271 if (File.Exists (filePath)) {
272 returnUrl = UrlUtils.Combine (returnUrl, indexFile);
279 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
284 static string GetHexString (string str)
286 return GetHexString (Encoding.UTF8.GetBytes (str));
289 static string GetHexString (byte [] bytes)
291 StringBuilder result = new StringBuilder (bytes.Length * 2);
292 foreach (byte b in bytes)
293 result.AppendFormat ("{0:X2}", (int) b);
295 return result.ToString ();
298 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
300 if (password == null)
301 throw new ArgumentNullException ("password");
303 if (passwordFormat == null)
304 throw new ArgumentNullException ("passwordFormat");
307 if (String.Compare (passwordFormat, "MD5", true) == 0) {
308 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
309 } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
310 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
312 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
315 return GetHexString (bytes);
318 public static void Initialize ()
327 HttpContext context = HttpContext.Current;
329 throw new HttpException ("Context is null!");
331 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
332 if (authConfig != null) {
333 cookieName = authConfig.CookieName;
334 timeout = authConfig.Timeout;
335 cookiePath = authConfig.CookiePath;
336 protection = authConfig.Protection;
338 requireSSL = authConfig.RequireSSL;
339 slidingExpiration = authConfig.SlidingExpiration;
342 cookieName = ".MONOAUTH";
345 protection = FormsProtectionEnum.All;
347 slidingExpiration = true;
351 // IV is 8 bytes long for 3DES
352 init_vector = new byte [8];
353 int len = cookieName.Length;
354 for (int i = 0; i < 8; i++) {
358 init_vector [i] = (byte) cookieName [i];
365 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
367 RedirectFromLoginPage (userName, createPersistentCookie, null);
370 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
372 if (userName == null)
376 SetAuthCookie (userName, createPersistentCookie, strCookiePath);
377 HttpResponse resp = HttpContext.Current.Response;
378 resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
381 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
386 DateTime now = DateTime.Now;
387 TimeSpan toIssue = now - tOld.IssueDate;
388 TimeSpan toExpiration = tOld.Expiration - now;
389 if (toExpiration > toIssue)
392 FormsAuthenticationTicket tNew = tOld.Clone ();
393 tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
397 public static void SetAuthCookie (string userName, bool createPersistentCookie)
400 SetAuthCookie (userName, createPersistentCookie, cookiePath);
403 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
405 HttpContext context = HttpContext.Current;
407 throw new HttpException ("Context is null!");
409 HttpResponse response = context.Response;
410 if (response == null)
411 throw new HttpException ("Response is null!");
413 response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
416 public static void SignOut ()
420 HttpContext context = HttpContext.Current;
422 throw new HttpException ("Context is null!");
424 HttpResponse response = context.Response;
425 if (response == null)
426 throw new HttpException ("Response is null!");
428 response.Cookies.MakeCookieExpire (cookieName, cookiePath);
431 public static string FormsCookieName
439 public static string FormsCookiePath
447 public static bool RequireSSL {
454 public static bool SlidingExpiration {
457 return slidingExpiration;