2005-02-06 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[mono.git] / mcs / class / System.Web / System.Web.Security / FormsAuthentication.cs
1 //
2 // System.Web.Security.FormsAuthentication
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 //
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Collections;
33 using System.IO;
34 using System.Security.Cryptography;
35 using System.Text;
36 using System.Web;
37 using System.Web.Configuration;
38 using System.Web.Util;
39
40 namespace System.Web.Security
41 {
42         public sealed class FormsAuthentication
43         {
44                 static string authConfigPath = "system.web/authentication";
45                 static bool initialized;
46                 static string cookieName;
47                 static string cookiePath;
48                 static int timeout;
49                 static FormsProtectionEnum protection;
50                 static object locker = new object ();
51 #if NET_1_1
52                 static bool requireSSL;
53                 static bool slidingExpiration;
54 #endif
55
56                 // same names and order used in xsp
57                 static string [] indexFiles = { "index.aspx",
58                                                 "Default.aspx",
59                                                 "default.aspx",
60                                                 "index.html",
61                                                 "index.htm" };
62
63                 public static bool Authenticate (string name, string password)
64                 {
65                         if (name == null || password == null)
66                                 return false;
67
68                         Initialize ();
69                         HttpContext context = HttpContext.Current;
70                         if (context == null)
71                                 throw new HttpException ("Context is null!");
72
73                         AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
74                         Hashtable users = config.CredentialUsers;
75                         string stored = users [name] as string;
76                         if (stored == null)
77                                 return false;
78
79                         switch (config.PasswordFormat) {
80                         case FormsAuthPasswordFormat.Clear:
81                                 /* Do nothing */
82                                 break;
83                         case FormsAuthPasswordFormat.MD5:
84                                 password = HashPasswordForStoringInConfigFile (password, "MD5");
85                                 break;
86                         case FormsAuthPasswordFormat.SHA1:
87                                 password = HashPasswordForStoringInConfigFile (password, "SHA1");
88                                 break;
89                         }
90
91                         return (password == stored);
92                 }
93
94                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
95                 {
96                         if (encryptedTicket == null || encryptedTicket == String.Empty)
97                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
98
99                         Initialize ();
100                         byte [] bytes = MachineKeyConfigHandler.GetBytes (encryptedTicket, encryptedTicket.Length);
101                         string decrypted = Encoding.ASCII.GetString (bytes);
102                         FormsAuthenticationTicket ticket = null;
103                         try {
104                                 string [] values = decrypted.Split ((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7);
105                                 if (values.Length != 8)
106                                         throw new Exception (values.Length + " " + encryptedTicket);
107
108
109                                 ticket = new FormsAuthenticationTicket (Int32.Parse (values [0]),
110                                                                         values [1],
111                                                                         new DateTime (Int64.Parse (values [2])),
112                                                                         new DateTime (Int64.Parse (values [3])),
113                                                                         (values [4] == "1"),
114                                                                         values [5],
115                                                                         values [6]);
116                         } catch (Exception) {
117                                 ticket = null;
118                         }
119
120                         return ticket;
121                 }
122
123                 public static string Encrypt (FormsAuthenticationTicket ticket)
124                 {
125                         if (ticket == null)
126                                 throw new ArgumentNullException ("ticket");
127
128                         Initialize ();
129                         StringBuilder allTicket = new StringBuilder ();
130                         allTicket.Append (ticket.Version);
131                         allTicket.Append ('\u0001');
132                         allTicket.Append (ticket.Name);
133                         allTicket.Append ('\u0002');
134                         allTicket.Append (ticket.IssueDate.Ticks);
135                         allTicket.Append ('\u0003');
136                         allTicket.Append (ticket.Expiration.Ticks);
137                         allTicket.Append ('\u0004');
138                         allTicket.Append (ticket.IsPersistent ? '1' : '0');
139                         allTicket.Append ('\u0005');
140                         allTicket.Append (ticket.UserData);
141                         allTicket.Append ('\u0006');
142                         allTicket.Append (ticket.CookiePath);
143                         allTicket.Append ('\u0007');
144                         //if (protection == FormsProtectionEnum.None)
145                                 return GetHexString (allTicket.ToString ());
146                         //TODO: encrypt and validate
147                 }
148
149                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
150                 {
151                         return GetAuthCookie (userName, createPersistentCookie, null);
152                 }
153
154                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
155                 {
156                         Initialize ();
157
158                         if (userName == null)
159                                 userName = String.Empty;
160
161                         if (strCookiePath == null || strCookiePath.Length == 0)
162                                 strCookiePath = cookiePath;
163
164                         DateTime now = DateTime.Now;
165                         DateTime then;
166                         if (createPersistentCookie)
167                                 then = now.AddYears (50);
168                         else
169                                 then = now.AddMinutes (timeout);
170
171                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
172                                                                                           userName,
173                                                                                           now,
174                                                                                           then,
175                                                                                           createPersistentCookie,
176                                                                                           String.Empty,
177                                                                                           cookiePath);
178
179                         if (!createPersistentCookie)
180                                 then = DateTime.MinValue;
181
182                         return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
183                 }
184
185                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
186                 {
187                         if (userName == null)
188                                 return null;
189
190                         //TODO: what's createPersistentCookie used for?
191                         Initialize ();
192                         HttpRequest request = HttpContext.Current.Request;
193                         string returnUrl = request ["RETURNURL"];
194                         if (returnUrl != null)
195                                 return returnUrl;
196
197                         returnUrl = request.ApplicationPath;
198                         string apppath = request.PhysicalApplicationPath;
199                         bool found = false;
200
201                         foreach (string indexFile in indexFiles) {
202                                 string filePath = Path.Combine (apppath, indexFile);
203                                 if (File.Exists (filePath)) {
204                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
205                                         found = true;
206                                         break;
207                                 }
208                         }
209
210                         if (!found)
211                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
212
213                         return returnUrl;
214                 }
215
216                 static string GetHexString (string str)
217                 {
218                         return GetHexString (Encoding.ASCII.GetBytes (str));
219                 }
220
221                 static string GetHexString (byte [] bytes)
222                 {
223                         StringBuilder result = new StringBuilder (bytes.Length * 2);
224                         foreach (byte b in bytes)
225                                 result.AppendFormat ("{0:x2}", (int) b);
226
227                         return result.ToString ();
228                 }
229
230                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
231                 {
232                         if (password == null)
233                                 throw new ArgumentNullException ("password");
234
235                         if (passwordFormat == null)
236                                 throw new ArgumentNullException ("passwordFormat");
237
238                         byte [] bytes;
239                         if (String.Compare (passwordFormat, "MD5", true) == 0) {
240                                 bytes = MD5.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
241                         } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
242                                 bytes = SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
243                         } else {
244                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
245                         }
246
247                         return GetHexString (bytes);
248                 }
249
250                 public static void Initialize ()
251                 {
252                         if (initialized)
253                                 return;
254
255                         lock (locker) {
256                                 if (initialized)
257                                         return;
258
259                                 HttpContext context = HttpContext.Current;
260                                 if (context == null)
261                                         throw new HttpException ("Context is null!");
262
263                                 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
264                                 if (authConfig != null) {
265                                         cookieName = authConfig.CookieName;
266                                         timeout = authConfig.Timeout;
267                                         cookiePath = authConfig.CookiePath;
268                                         protection = authConfig.Protection;
269 #if NET_1_1
270                                         requireSSL = authConfig.RequireSSL;
271                                         slidingExpiration = authConfig.SlidingExpiration;
272 #endif
273                                 } else {
274                                         cookieName = ".MONOAUTH";
275                                         timeout = 30;
276                                         cookiePath = "/";
277                                         protection = FormsProtectionEnum.All;
278 #if NET_1_1
279                                         slidingExpiration = true;
280 #endif
281                                 }
282
283                                 initialized = true;
284                         }
285                 }
286
287                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
288                 {
289                         RedirectFromLoginPage (userName, createPersistentCookie, null);
290                 }
291
292                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
293                 {
294                         if (userName == null)
295                                 return;
296
297                         Initialize ();
298                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
299                         HttpResponse resp = HttpContext.Current.Response;
300                         resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
301                 }
302
303                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
304                 {
305                         if (tOld == null)
306                                 return null;
307
308                         DateTime now = DateTime.Now;
309                         TimeSpan toIssue = now - tOld.IssueDate;
310                         TimeSpan toExpiration = tOld.Expiration - now;
311                         if (toExpiration > toIssue)
312                                 return tOld;
313
314                         FormsAuthenticationTicket tNew = tOld.Clone ();
315                         tNew.SetDates (now, now + (tOld.Expiration - tOld.IssueDate));
316                         return tNew;
317                 }
318
319                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
320                 {
321                         Initialize ();
322                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
323                 }
324
325                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
326                 {
327                         HttpContext context = HttpContext.Current;
328                         if (context == null)
329                                 throw new HttpException ("Context is null!");
330
331                         HttpResponse response = context.Response;
332                         if (response == null)
333                                 throw new HttpException ("Response is null!");
334
335                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
336                 }
337
338                 public static void SignOut ()
339                 {
340                         Initialize ();
341
342                         HttpContext context = HttpContext.Current;
343                         if (context == null)
344                                 throw new HttpException ("Context is null!");
345
346                         HttpResponse response = context.Response;
347                         if (response == null)
348                                 throw new HttpException ("Response is null!");
349
350                         response.Cookies.MakeCookieExpire (cookieName, cookiePath);
351                 }
352
353                 public static string FormsCookieName
354                 {
355                         get {
356                                 Initialize ();
357                                 return cookieName;
358                         }
359                 }
360
361                 public static string FormsCookiePath
362                 {
363                         get {
364                                 Initialize ();
365                                 return cookiePath;
366                         }
367                 }
368 #if NET_1_1
369                 public static bool RequireSSL {
370                         get {
371                                 Initialize ();
372                                 return requireSSL;
373                         }
374                 }
375
376                 public static bool SlidingExpiration {
377                         get {
378                                 Initialize ();
379                                 return slidingExpiration;
380                         }
381                 }
382 #endif
383         }
384 }
385