Add licensing info
[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 #if NET_1_1
51                 static bool requireSSL;
52                 static bool slidingExpiration;
53 #endif
54
55                 // same names and order used in xsp
56                 static string [] indexFiles = { "index.aspx",
57                                                 "Default.aspx",
58                                                 "default.aspx",
59                                                 "index.html",
60                                                 "index.htm" };
61
62                 public static bool Authenticate (string name, string password)
63                 {
64                         if (name == null || password == null)
65                                 return false;
66
67                         Initialize ();
68                         HttpContext context = HttpContext.Current;
69                         if (context == null)
70                                 throw new HttpException ("Context is null!");
71
72                         AuthConfig config = context.GetConfig (authConfigPath) as AuthConfig;
73                         Hashtable users = config.CredentialUsers;
74                         string stored = users [name] as string;
75                         if (stored == null)
76                                 return false;
77
78                         switch (config.PasswordFormat) {
79                         case FormsAuthPasswordFormat.Clear:
80                                 /* Do nothing */
81                                 break;
82                         case FormsAuthPasswordFormat.MD5:
83                                 stored = HashPasswordForStoringInConfigFile (stored, "MD5");
84                                 break;
85                         case FormsAuthPasswordFormat.SHA1:
86                                 stored = HashPasswordForStoringInConfigFile (stored, "SHA1");
87                                 break;
88                         }
89
90                         return (password == stored);
91                 }
92
93                 public static FormsAuthenticationTicket Decrypt (string encryptedTicket)
94                 {
95                         if (encryptedTicket == null || encryptedTicket == String.Empty)
96                                 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
97
98                         Initialize ();
99                         byte [] bytes = MachineKeyConfigHandler.GetBytes (encryptedTicket, encryptedTicket.Length);
100                         string decrypted = Encoding.ASCII.GetString (bytes);
101                         FormsAuthenticationTicket ticket = null;
102                         try {
103                                 string [] values = decrypted.Split ((char) 1, (char) 2, (char) 3, (char) 4, (char) 5, (char) 6, (char) 7);
104                                 if (values.Length != 8)
105                                         throw new Exception (values.Length + " " + encryptedTicket);
106
107
108                                 ticket = new FormsAuthenticationTicket (Int32.Parse (values [0]),
109                                                                         values [1],
110                                                                         new DateTime (Int64.Parse (values [2])),
111                                                                         new DateTime (Int64.Parse (values [3])),
112                                                                         (values [4] == "1"),
113                                                                         values [5],
114                                                                         values [6]);
115                         } catch (Exception) {
116                                 ticket = null;
117                         }
118
119                         return ticket;
120                 }
121
122                 public static string Encrypt (FormsAuthenticationTicket ticket)
123                 {
124                         if (ticket == null)
125                                 throw new ArgumentNullException ("ticket");
126
127                         Initialize ();
128                         StringBuilder allTicket = new StringBuilder ();
129                         allTicket.Append (ticket.Version);
130                         allTicket.Append ('\u0001');
131                         allTicket.Append (ticket.Name);
132                         allTicket.Append ('\u0002');
133                         allTicket.Append (ticket.IssueDate.Ticks);
134                         allTicket.Append ('\u0003');
135                         allTicket.Append (ticket.Expiration.Ticks);
136                         allTicket.Append ('\u0004');
137                         allTicket.Append (ticket.IsPersistent ? '1' : '0');
138                         allTicket.Append ('\u0005');
139                         allTicket.Append (ticket.UserData);
140                         allTicket.Append ('\u0006');
141                         allTicket.Append (ticket.CookiePath);
142                         allTicket.Append ('\u0007');
143                         //if (protection == FormsProtectionEnum.None)
144                                 return GetHexString (allTicket.ToString ());
145                         //TODO: encrypt and validate
146                 }
147
148                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie)
149                 {
150                         return GetAuthCookie (userName, createPersistentCookie, null);
151                 }
152
153                 public static HttpCookie GetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
154                 {
155                         Initialize ();
156
157                         if (userName == null)
158                                 userName = String.Empty;
159
160                         if (strCookiePath == null || strCookiePath.Length == 0)
161                                 strCookiePath = cookiePath;
162
163                         DateTime now = DateTime.Now;
164                         DateTime then;
165                         if (createPersistentCookie)
166                                 then = now.AddYears (50);
167                         else
168                                 then = now.AddMinutes (timeout);
169
170                         FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1,
171                                                                                           userName,
172                                                                                           now,
173                                                                                           then,
174                                                                                           createPersistentCookie,
175                                                                                           String.Empty,
176                                                                                           cookiePath);
177
178                         if (!createPersistentCookie)
179                                 then = DateTime.MinValue;
180
181                         return new HttpCookie (cookieName, Encrypt (ticket), strCookiePath, then);
182                 }
183
184                 public static string GetRedirectUrl (string userName, bool createPersistentCookie)
185                 {
186                         if (userName == null)
187                                 return null;
188
189                         //TODO: what's createPersistentCookie used for?
190                         Initialize ();
191                         HttpRequest request = HttpContext.Current.Request;
192                         string returnUrl = request ["RETURNURL"];
193                         if (returnUrl != null)
194                                 return returnUrl;
195
196                         returnUrl = request.ApplicationPath;
197                         string apppath = request.PhysicalApplicationPath;
198                         bool found = false;
199
200                         foreach (string indexFile in indexFiles) {
201                                 string filePath = Path.Combine (apppath, indexFile);
202                                 if (File.Exists (filePath)) {
203                                         returnUrl = UrlUtils.Combine (returnUrl, indexFile);
204                                         found = true;
205                                         break;
206                                 }
207                         }
208
209                         if (!found)
210                                 returnUrl = UrlUtils.Combine (returnUrl, "index.aspx");
211
212                         return returnUrl;
213                 }
214
215                 static string GetHexString (string str)
216                 {
217                         return GetHexString (Encoding.ASCII.GetBytes (str));
218                 }
219
220                 static string GetHexString (byte [] bytes)
221                 {
222                         StringBuilder result = new StringBuilder (bytes.Length * 2);
223                         foreach (byte b in bytes)
224                                 result.AppendFormat ("{0:x2}", (int) b);
225
226                         return result.ToString ();
227                 }
228
229                 public static string HashPasswordForStoringInConfigFile (string password, string passwordFormat)
230                 {
231                         if (password == null)
232                                 throw new ArgumentNullException ("password");
233
234                         if (passwordFormat == null)
235                                 throw new ArgumentNullException ("passwordFormat");
236
237                         byte [] bytes;
238                         if (String.Compare (passwordFormat, "MD5", true) == 0) {
239                                 bytes = MD5.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
240                         } else if (String.Compare (passwordFormat, "SHA1", true) == 0) {
241                                 bytes = SHA1.Create ().ComputeHash (Encoding.ASCII.GetBytes (password));
242                         } else {
243                                 throw new ArgumentException ("The format must be either MD5 or SHA1", "passwordFormat");
244                         }
245
246                         return GetHexString (bytes);
247                 }
248
249                 public static void Initialize ()
250                 {
251                         if (initialized)
252                                 return;
253
254                         lock (typeof (FormsAuthentication)) {
255                                 if (initialized)
256                                         return;
257
258                                 HttpContext context = HttpContext.Current;
259                                 if (context == null)
260                                         throw new HttpException ("Context is null!");
261
262                                 AuthConfig authConfig = context.GetConfig (authConfigPath) as AuthConfig;
263                                 if (authConfig != null) {
264                                         cookieName = authConfig.CookieName;
265                                         timeout = authConfig.Timeout;
266                                         cookiePath = authConfig.CookiePath;
267                                         protection = authConfig.Protection;
268 #if NET_1_1
269                                         requireSSL = authConfig.RequireSSL;
270                                         slidingExpiration = authConfig.SlidingExpiration;
271 #endif
272                                 } else {
273                                         cookieName = ".MONOAUTH";
274                                         timeout = 30;
275                                         cookiePath = "/";
276                                         protection = FormsProtectionEnum.All;
277 #if NET_1_1
278                                         slidingExpiration = true;
279 #endif
280                                 }
281
282                                 initialized = true;
283                         }
284                 }
285
286                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie)
287                 {
288                         RedirectFromLoginPage (userName, createPersistentCookie, null);
289                 }
290
291                 public static void RedirectFromLoginPage (string userName, bool createPersistentCookie, string strCookiePath)
292                 {
293                         if (userName == null)
294                                 return;
295
296                         Initialize ();
297                         SetAuthCookie (userName, createPersistentCookie, strCookiePath);
298                         HttpResponse resp = HttpContext.Current.Response;
299                         resp.Redirect (GetRedirectUrl (userName, createPersistentCookie), false);
300                 }
301
302                 public static FormsAuthenticationTicket RenewTicketIfOld (FormsAuthenticationTicket tOld)
303                 {
304                         if (tOld == null)
305                                 return null;
306
307                         DateTime now = DateTime.Now;
308                         TimeSpan toIssue = now - tOld.IssueDate;
309                         TimeSpan toExpiration = tOld.Expiration - now;
310                         if (toExpiration > toIssue)
311                                 return tOld;
312
313                         FormsAuthenticationTicket tNew = tOld.Clone ();
314                         tNew.SetDates (now, now - toExpiration + toIssue);
315                         return tNew;
316                 }
317
318                 public static void SetAuthCookie (string userName, bool createPersistentCookie)
319                 {
320                         Initialize ();
321                         SetAuthCookie (userName, createPersistentCookie, cookiePath);
322                 }
323
324                 public static void SetAuthCookie (string userName, bool createPersistentCookie, string strCookiePath)
325                 {
326                         HttpContext context = HttpContext.Current;
327                         if (context == null)
328                                 throw new HttpException ("Context is null!");
329
330                         HttpResponse response = context.Response;
331                         if (response == null)
332                                 throw new HttpException ("Response is null!");
333
334                         response.Cookies.Add (GetAuthCookie (userName, createPersistentCookie, strCookiePath));
335                 }
336
337                 public static void SignOut ()
338                 {
339                         Initialize ();
340
341                         HttpContext context = HttpContext.Current;
342                         if (context == null)
343                                 throw new HttpException ("Context is null!");
344
345                         HttpResponse response = context.Response;
346                         if (response == null)
347                                 throw new HttpException ("Response is null!");
348
349                         response.Cookies.MakeCookieExpire (cookieName, cookiePath);
350                 }
351
352                 public static string FormsCookieName
353                 {
354                         get {
355                                 Initialize ();
356                                 return cookieName;
357                         }
358                 }
359
360                 public static string FormsCookiePath
361                 {
362                         get {
363                                 Initialize ();
364                                 return cookiePath;
365                         }
366                 }
367 #if NET_1_1
368                 public static bool RequireSSL {
369                         get {
370                                 Initialize ();
371                                 return requireSSL;
372                         }
373                 }
374
375                 public static bool SlidingExpiration {
376                         get {
377                                 Initialize ();
378                                 return slidingExpiration;
379                         }
380                 }
381 #endif
382         }
383 }
384