2 // System.Web.Security.FormsAuthenticationModule
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
30 using System.ComponentModel;
31 using System.Security.Permissions;
32 using System.Security.Principal;
34 using System.Web.Configuration;
35 using System.Web.Util;
37 namespace System.Web.Security
39 // CAS - no InheritanceDemand here as the class is sealed
40 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
41 public sealed class FormsAuthenticationModule : IHttpModule
43 static readonly object authenticateEvent = new object ();
46 AuthenticationSection _config = null;
48 AuthConfig _config = null;
50 bool isConfigInitialized = false;
51 EventHandlerList events = new EventHandlerList ();
53 public event FormsAuthenticationEventHandler Authenticate {
54 add { events.AddHandler (authenticateEvent, value); }
55 remove { events.RemoveHandler (authenticateEvent, value); }
58 void InitConfig (HttpContext context)
60 if(isConfigInitialized)
63 _config = (AuthenticationSection) WebConfigurationManager.GetSection ("system.web/authentication");
65 _config = (AuthConfig) context.GetConfig ("system.web/authentication");
67 isConfigInitialized = true;
70 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
71 public FormsAuthenticationModule ()
75 public void Dispose ()
79 public void Init (HttpApplication app)
81 app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest);
82 app.EndRequest += new EventHandler (OnEndRequest);
85 void OnAuthenticateRequest (object sender, EventArgs args)
87 HttpApplication app = (HttpApplication) sender;
88 HttpContext context = app.Context;
93 bool slidingExpiration;
96 if (_config == null || _config.Mode != AuthenticationMode.Forms) {
101 cookieName = _config.Forms.Name;
102 cookiePath = _config.Forms.Path;
103 loginPage = _config.Forms.LoginUrl;
104 slidingExpiration = _config.Forms.SlidingExpiration;
106 cookieName = _config.CookieName;
107 cookiePath = _config.CookiePath;
108 loginPage = _config.LoginUrl;
109 slidingExpiration = _config.SlidingExpiration;
113 string loginPath = null;
115 reqPath = context.Request.PhysicalPath;
116 loginPath = context.Request.MapPath (loginPage);
119 context.SkipAuthorization = (reqPath == loginPath);
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;
128 FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context);
129 FormsAuthenticationEventHandler eh = events [authenticateEvent] as FormsAuthenticationEventHandler;
133 bool contextUserNull = (context.User == null);
134 if (formArgs.User != null || !contextUserNull) {
136 context.User = formArgs.User;
140 HttpCookie cookie = context.Request.Cookies [cookieName];
141 if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now))
144 FormsAuthenticationTicket ticket = null;
146 ticket = FormsAuthentication.Decrypt (cookie.Value);
148 catch (ArgumentException) {
149 // incorrect cookie value, suppress the exception
152 if (ticket == null || (!ticket.IsPersistent && ticket.Expired))
155 FormsAuthenticationTicket oldticket = ticket;
156 if (slidingExpiration)
157 ticket = FormsAuthentication.RenewTicketIfOld (ticket);
159 context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]);
161 if (cookie.Expires == DateTime.MinValue && oldticket == ticket)
164 cookie.Value = FormsAuthentication.Encrypt (ticket);
165 cookie.Path = cookiePath;
166 if (ticket.IsPersistent)
167 cookie.Expires = ticket.Expiration;
169 context.Response.Cookies.Add (cookie);
172 void OnEndRequest (object sender, EventArgs args)
174 HttpApplication app = (HttpApplication) sender;
175 HttpContext context = app.Context;
176 if (context.Response.StatusCode != 401 || context.Request.QueryString ["ReturnUrl"] != null)
180 InitConfig (context);
182 loginPage = _config.Forms.LoginUrl;
184 loginPage = _config.LoginUrl;
186 if (_config == null || _config.Mode != AuthenticationMode.Forms)
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);