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 ();
53 static bool initialized;
54 static string cookieName;
55 static string cookiePath;
57 static FormsProtectionEnum protection;
58 static bool requireSSL;
59 static bool slidingExpiration;
60 static string cookie_domain;
61 static HttpCookieMode cookie_mode;
62 static bool cookies_supported;
63 static string default_url;
64 static bool enable_crossapp_redirects;
65 static string login_url;
66 // same names and order used in xsp
67 static string [] indexFiles = { "index.aspx",
72 public static TimeSpan Timeout {
76 public static bool IsEnabled {
77 get { return initialized; }
80 public static void EnableFormsAuthentication (NameValueCollection configurationData)
82 BuildManager.AssertPreStartMethodsRunning ();
83 if (configurationData == null || configurationData.Count == 0)
86 string value = configurationData ["loginUrl"];
87 if (!String.IsNullOrEmpty (value))
90 value = configurationData ["defaultUrl"];
91 if (!String.IsNullOrEmpty (value))
94 public FormsAuthentication ()
98 public static bool Authenticate (string name, string password)
100 if (name == null || password == null)
104 HttpContext context = HttpContext.Current;
106 throw new HttpException ("Context is null!");
108 name = name.ToLower (Helpers.InvariantCulture);
110 AuthenticationSection section = (AuthenticationSection) WebConfigurationManager.GetSection (authConfigPath);
111 FormsAuthenticationCredentials config = section.Forms.Credentials;
112 FormsAuthenticationUser user = config.Users[name];
113 string stored = null;
116 stored = user.Password;
121 bool caseInsensitive = true;
122 switch (config.PasswordFormat) {
123 case FormsAuthPasswordFormat.Clear:
124 caseInsensitive = false;
127 case FormsAuthPasswordFormat.MD5:
128 password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
130 case FormsAuthPasswordFormat.SHA1:
131 password = HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
135 return String.Compare (password, stored, caseInsensitive ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0;
138 static FormsAuthenticationTicket Decrypt2 (byte [] bytes)
140 if (protection == FormsProtectionEnum.None)
141 return FormsAuthenticationTicket.FromByteArray (bytes);
143 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
144 byte [] result = null;
145 if (protection == FormsProtectionEnum.All) {
146 result = MachineKeySectionUtils.VerifyDecrypt (config, bytes);
147 } else if (protection == FormsProtectionEnum.Encryption) {
148 result = MachineKeySectionUtils.Decrypt (config, bytes);
149 } else if (protection == FormsProtectionEnum.Validation) {
150 result = MachineKeySectionUtils.Verify (config, bytes);
153 return FormsAuthenticationTicket.FromByteArray (result);
156 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
158 if (String.IsNullOrEmpty (encryptedTicket))
159 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
163 FormsAuthenticationTicket ticket;
164 byte [] bytes = Convert.FromBase64String (encryptedTicket);
167 ticket = Decrypt2 (bytes);
168 } catch (Exception) {
175 public static string Encrypt (FormsAuthenticationTicket ticket)
178 throw new ArgumentNullException ("ticket");
181 byte [] ticket_bytes = ticket.ToByteArray ();
182 if (protection == FormsProtectionEnum.None)
183 return Convert.ToBase64String (ticket_bytes);
185 byte [] result = null;
186 MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection (machineKeyConfigPath);
188 if (protection == FormsProtectionEnum.All) {
189 result = MachineKeySectionUtils.EncryptSign (config, ticket_bytes);
190 } else if (protection == FormsProtectionEnum.Encryption) {
191 result = MachineKeySectionUtils.Encrypt (config, ticket_bytes);
192 } else if (protection == FormsProtectionEnum.Validation) {
193 result = MachineKeySectionUtils.Sign (config, ticket_bytes);
196 return Convert.ToBase64String (result);
199 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
201 return GetAuthCookie (userName, createPersistentCookie, null);
204 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
208 if (userName == null)
209 userName = String.Empty;
211 if (strCookiePath == null || strCookiePath.Length == 0)
212 strCookiePath = cookiePath;
214 DateTime now = DateTime.Now;
216 if (createPersistentCookie)
217 then = now.AddMinutes(timeout);
219 then = DateTime.MinValue;
221 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
224 createPersistentCookie?then:now.AddYears (50),
225 createPersistentCookie,
229 HttpCookie cookie = new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
231 cookie.Secure = true;
232 if (!String.IsNullOrEmpty (cookie_domain))
233 cookie.Domain = cookie_domain;
238 internal static string ReturnUrl {
239 get { return HttpContext.Current.Request ["RETURNURL"]; }
242 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
244 if (userName == null)
248 HttpRequest request = HttpContext.Current.Request;
249 string returnUrl = ReturnUrl;
250 if (returnUrl != null)
253 returnUrl = request.ApplicationPath;
254 string apppath = request.PhysicalApplicationPath;
257 foreach (string indexFile in indexFiles) {
258 string filePath = Path.Combine (apppath, indexFile);
259 if (File.Exists (filePath)) {
260 returnUrl = UrlUtils.Combine (returnUrl, indexFile);
267 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
272 static string HashPasswordForStoringInConfigFile (string password, FormsAuthPasswordFormat passwordFormat)
274 if (password == null)
275 throw new ArgumentNullException ("password");
278 switch (passwordFormat) {
279 case FormsAuthPasswordFormat.MD5:
280 bytes = MD5.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
283 case FormsAuthPasswordFormat.SHA1:
284 bytes = SHA1.Create ().ComputeHash (Encoding.UTF8.GetBytes (password));
288 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
291 return MachineKeySectionUtils.GetHexString (bytes);
294 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
296 if (password == null)
297 throw new ArgumentNullException ("password");
299 if (passwordFormat == null)
300 throw new ArgumentNullException ("passwordFormat");
302 if (String.Compare (passwordFormat, "MD5", StringComparison.OrdinalIgnoreCase) == 0) {
303 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.MD5);
304 } else if (String.Compare (passwordFormat, "SHA1", StringComparison.OrdinalIgnoreCase) == 0) {
305 return HashPasswordForStoringInConfigFile (password, FormsAuthPasswordFormat.SHA1);
307 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
311 public static void Initialize ()
320 AuthenticationSection section = (AuthenticationSection)WebConfigurationManager.GetSection (authConfigPath);
321 FormsAuthenticationConfiguration config = section.Forms;
323 cookieName = config.Name;
324 Timeout = config.Timeout;
325 timeout = (int)config.Timeout.TotalMinutes;
326 cookiePath = config.Path;
327 protection = config.Protection;
328 requireSSL = config.RequireSSL;
329 slidingExpiration = config.SlidingExpiration;
330 cookie_domain = config.Domain;
331 cookie_mode = config.Cookieless;
332 cookies_supported = true; /* XXX ? */
333 if (!String.IsNullOrEmpty (default_url))
334 default_url = MapUrl (default_url);
336 default_url = MapUrl(config.DefaultUrl);
337 enable_crossapp_redirects = config.EnableCrossAppRedirects;
338 if (!String.IsNullOrEmpty (login_url))
339 login_url = MapUrl (login_url);
341 login_url = MapUrl(config.LoginUrl);
347 static string MapUrl (string url) {
348 if (UrlUtils.IsRelativeUrl (url))
349 return UrlUtils.Combine (HttpRuntime.AppDomainAppVirtualPath, url);
351 return UrlUtils.ResolveVirtualPathFromAppAbsolute (url);
354 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
356 RedirectFromLoginPage (userName, createPersistentCookie, null);
359 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
361 if (userName == null)
365 SetAuthCookie (userName, createPersistentCookie, strCookiePath);
366 Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
369 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
374 DateTime now = DateTime.Now;
375 TimeSpan toIssue = now - tOld.IssueDate;
376 TimeSpan toExpiration = tOld.Expiration - now;
377 if (toExpiration > toIssue)
380 FormsAuthenticationTicket tNew = tOld.Clone ();
381 tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
385 public static void SetAuthCookie (string userName, bool createPersistentCookie)
388 SetAuthCookie (userName, createPersistentCookie, cookiePath);
391 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
393 HttpContext context = HttpContext.Current;
395 throw new HttpException ("Context is null!");
397 HttpResponse response = context.Response;
398 if (response == null)
399 throw new HttpException ("Response is null!");
401 response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
404 public static void SignOut ()
408 HttpContext context = HttpContext.Current;
410 throw new HttpException ("Context is null!");
412 HttpResponse response = context.Response;
413 if (response == null)
414 throw new HttpException ("Response is null!");
416 HttpCookieCollection cc = response.Cookies;
417 cc.Remove (cookieName);
418 HttpCookie expiration_cookie = new HttpCookie (cookieName, String.Empty);
419 expiration_cookie.Expires = new DateTime (1999, 10, 12);
420 expiration_cookie.Path = cookiePath;
421 if (!String.IsNullOrEmpty (cookie_domain))
422 expiration_cookie.Domain = cookie_domain;
423 cc.Add (expiration_cookie);
424 Roles.DeleteCookie ();
427 public static string FormsCookieName
435 public static string FormsCookiePath
443 public static bool RequireSSL {
450 public static bool SlidingExpiration {
453 return slidingExpiration;
457 public static string CookieDomain {
458 get { Initialize (); return cookie_domain; }
461 public static HttpCookieMode CookieMode {
462 get { Initialize (); return cookie_mode; }
465 public static bool CookiesSupported {
466 get { Initialize (); return cookies_supported; }
469 public static string DefaultUrl {
470 get { Initialize (); return default_url; }
473 public static bool EnableCrossAppRedirects {
474 get { Initialize (); return enable_crossapp_redirects; }
477 public static string LoginUrl {
478 get { Initialize (); return login_url; }
481 public static void RedirectToLoginPage ()
486 [MonoTODO ("needs more tests")]
487 public static void RedirectToLoginPage (string extraQueryString)
489 // TODO: if ? is in LoginUrl (legal?), ? in query (legal?) ...
490 Redirect (LoginUrl + "?" + extraQueryString);
493 static void Redirect (string url)
495 HttpContext.Current.Response.Redirect (url);
498 static void Redirect (string url, bool end)
500 HttpContext.Current.Response.Redirect (url, end);