2008-11-06 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web.Security / FormsAuthenticationModule.cs
1 //
2 // System.Web.Security.FormsAuthenticationModule
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System.ComponentModel;
31 using System.Security.Permissions;
32 using System.Security.Principal;
33 using System.Text;
34 using System.Web.Configuration;
35 using System.Web.Util;
36
37 namespace System.Web.Security
38 {
39         // CAS - no InheritanceDemand here as the class is sealed
40         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
41         public sealed class FormsAuthenticationModule : IHttpModule
42         {
43                 static readonly object authenticateEvent = new object ();
44                 
45 #if NET_2_0
46                 AuthenticationSection _config = null;
47 #else
48                 AuthConfig _config = null;
49 #endif
50                 bool isConfigInitialized = false;
51                 EventHandlerList events = new EventHandlerList ();
52                 
53                 public event FormsAuthenticationEventHandler Authenticate {
54                         add { events.AddHandler (authenticateEvent, value); }
55                         remove { events.RemoveHandler (authenticateEvent, value); }
56                 }
57                 
58                 void InitConfig (HttpContext context)
59                 {
60                         if(isConfigInitialized)
61                                 return;
62 #if NET_2_0
63                         _config = (AuthenticationSection) WebConfigurationManager.GetSection ("system.web/authentication");
64 #else
65                         _config = (AuthConfig) context.GetConfig ("system.web/authentication");
66 #endif
67                         isConfigInitialized = true;
68                 }
69
70                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
71                 public FormsAuthenticationModule ()
72                 {
73                 }
74
75                 public void Dispose ()
76                 {
77                 }
78
79                 public void Init (HttpApplication app)
80                 {
81                         app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest);
82                         app.EndRequest += new EventHandler (OnEndRequest);
83                 }
84
85                 void OnAuthenticateRequest (object sender, EventArgs args)
86                 {
87                         HttpApplication app = (HttpApplication) sender;
88                         HttpContext context = app.Context;
89
90                         string cookieName;
91                         string cookiePath;
92                         string loginPage;
93                         bool slidingExpiration;
94
95                         InitConfig (context);
96                         if (_config == null || _config.Mode != AuthenticationMode.Forms) {
97                                 return;
98                         }
99
100 #if NET_2_0
101                         cookieName = _config.Forms.Name;
102                         cookiePath = _config.Forms.Path;
103                         loginPage = _config.Forms.LoginUrl;
104                         slidingExpiration = _config.Forms.SlidingExpiration;
105 #else
106                         cookieName = _config.CookieName;
107                         cookiePath = _config.CookiePath;
108                         loginPage = _config.LoginUrl;
109                         slidingExpiration = _config.SlidingExpiration;
110 #endif
111
112                         string reqPath = "";
113                         string loginPath = null;
114                         try {
115                                 reqPath = context.Request.PhysicalPath;
116                                 loginPath = context.Request.MapPath (loginPage);
117                         } catch {} // ignore
118
119                         context.SkipAuthorization = (reqPath == loginPath);
120                         
121 #if NET_2_0
122                         //TODO: need to check that the handler is System.Web.Handlers.AssemblyResourceLoader type
123                         string filePath = context.Request.FilePath;
124                         if (filePath.Length > 15 && String.CompareOrdinal ("WebResource.axd", 0, filePath, filePath.Length - 15, 15) == 0)
125                                 context.SkipAuthorization = true;
126 #endif
127
128                         FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context);
129                         FormsAuthenticationEventHandler eh = events [authenticateEvent] as FormsAuthenticationEventHandler;
130                         if (eh != null)
131                                 eh (this, formArgs);
132
133                         bool contextUserNull = (context.User == null);
134                         if (formArgs.User != null || !contextUserNull) {
135                                 if (contextUserNull)
136                                         context.User = formArgs.User;
137                                 return;
138                         }
139                                 
140                         HttpCookie cookie = context.Request.Cookies [cookieName];
141                         if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now))
142                                 return;
143
144                         FormsAuthenticationTicket ticket = null;
145                         try {
146                                 ticket = FormsAuthentication.Decrypt (cookie.Value);
147                         }
148                         catch (ArgumentException) {
149                                 // incorrect cookie value, suppress the exception
150                                 return;
151                         }
152                         if (ticket == null || (!ticket.IsPersistent && ticket.Expired))
153                                 return;
154
155                         FormsAuthenticationTicket oldticket = ticket;
156                         if (slidingExpiration)
157                                 ticket = FormsAuthentication.RenewTicketIfOld (ticket);
158
159                         context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]);
160
161                         if (cookie.Expires == DateTime.MinValue && oldticket == ticket) 
162                                 return;
163
164                         cookie.Value = FormsAuthentication.Encrypt (ticket);
165                         cookie.Path = cookiePath;
166                         if (ticket.IsPersistent)
167                                 cookie.Expires = ticket.Expiration;
168
169                         context.Response.Cookies.Add (cookie);
170                 }
171
172                 void OnEndRequest (object sender, EventArgs args)
173                 {
174                         HttpApplication app = (HttpApplication) sender;
175                         HttpContext context = app.Context;
176                         if (context.Response.StatusCode != 401 || context.Request.QueryString ["ReturnUrl"] != null)
177                                 return;
178
179                         string loginPage;
180                         InitConfig (context);
181 #if NET_2_0
182                         loginPage = _config.Forms.LoginUrl;
183 #else
184                         loginPage = _config.LoginUrl;
185 #endif
186                         if (_config == null || _config.Mode != AuthenticationMode.Forms)
187                                 return;
188
189                         StringBuilder login = new StringBuilder ();
190                         login.Append (UrlUtils.Combine (context.Request.ApplicationPath, loginPage));
191                         login.AppendFormat ("?ReturnUrl={0}", HttpUtility.UrlEncode (context.Request.RawUrl));
192                         context.Response.Redirect (login.ToString (), false);
193                 }
194         }
195 }
196