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.Globalization;
32 using System.Security.Permissions;
33 using System.Security.Principal;
35 using System.Web.Configuration;
36 using System.Web.Util;
38 namespace System.Web.Security
40 // CAS - no InheritanceDemand here as the class is sealed
41 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
42 public sealed class FormsAuthenticationModule : IHttpModule
44 static readonly object authenticateEvent = new object ();
46 AuthenticationSection _config = null;
47 bool isConfigInitialized = false;
48 EventHandlerList events = new EventHandlerList ();
50 public event FormsAuthenticationEventHandler Authenticate {
51 add { events.AddHandler (authenticateEvent, value); }
52 remove { events.RemoveHandler (authenticateEvent, value); }
55 void InitConfig (HttpContext context)
57 if(isConfigInitialized)
59 _config = (AuthenticationSection) WebConfigurationManager.GetSection ("system.web/authentication");
60 isConfigInitialized = true;
63 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
64 public FormsAuthenticationModule ()
68 public void Dispose ()
72 public void Init (HttpApplication app)
74 app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest);
75 app.EndRequest += new EventHandler (OnEndRequest);
78 void OnAuthenticateRequest (object sender, EventArgs args)
80 HttpApplication app = (HttpApplication) sender;
81 HttpContext context = app.Context;
86 bool slidingExpiration;
89 if (_config == null || _config.Mode != AuthenticationMode.Forms) {
93 cookieName = _config.Forms.Name;
94 cookiePath = _config.Forms.Path;
95 loginPage = _config.Forms.LoginUrl;
96 slidingExpiration = _config.Forms.SlidingExpiration;
98 if (!VirtualPathUtility.IsRooted (loginPage))
99 loginPage = "~/" + loginPage;
101 string reqPath = String.Empty;
102 string loginPath = null;
104 reqPath = context.Request.PhysicalPath;
105 loginPath = context.Request.MapPath (loginPage);
108 context.SkipAuthorization = String.Compare (reqPath, loginPath, RuntimeHelpers.CaseInsensitive, Helpers.InvariantCulture) == 0;
110 //TODO: need to check that the handler is System.Web.Handlers.AssemblyResourceLoader type
111 string filePath = context.Request.FilePath;
112 if (filePath.Length > 15 && String.CompareOrdinal ("WebResource.axd", 0, filePath, filePath.Length - 15, 15) == 0)
113 context.SkipAuthorization = true;
115 FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context);
116 FormsAuthenticationEventHandler eh = events [authenticateEvent] as FormsAuthenticationEventHandler;
120 bool contextUserNull = (context.User == null);
121 if (formArgs.User != null || !contextUserNull) {
123 context.User = formArgs.User;
127 HttpCookie cookie = context.Request.Cookies [cookieName];
128 if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now))
131 FormsAuthenticationTicket ticket = null;
133 ticket = FormsAuthentication.Decrypt (cookie.Value);
135 catch (ArgumentException) {
136 // incorrect cookie value, suppress the exception
139 if (ticket == null || (!ticket.IsPersistent && ticket.Expired))
142 FormsAuthenticationTicket oldticket = ticket;
143 if (slidingExpiration)
144 ticket = FormsAuthentication.RenewTicketIfOld (ticket);
146 context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]);
148 if (cookie.Expires == DateTime.MinValue && oldticket == ticket)
151 cookie.Value = FormsAuthentication.Encrypt (ticket);
152 cookie.Path = cookiePath;
153 if (ticket.IsPersistent)
154 cookie.Expires = ticket.Expiration;
156 context.Response.Cookies.Add (cookie);
159 void OnEndRequest (object sender, EventArgs args)
161 HttpApplication app = (HttpApplication) sender;
162 HttpContext context = app.Context;
163 if (context.Response.StatusCode != 401 || context.Request.QueryString ["ReturnUrl"] != null)
166 if (context.Response.StatusCode == 401 && context.Response.SuppressFormsAuthenticationRedirect)
170 InitConfig (context);
171 loginPage = _config.Forms.LoginUrl;
172 if (_config == null || _config.Mode != AuthenticationMode.Forms)
175 StringBuilder login = new StringBuilder ();
176 login.Append (UrlUtils.Combine (context.Request.ApplicationPath, loginPage));
177 login.AppendFormat ("?ReturnUrl={0}", HttpUtility.UrlEncode (context.Request.RawUrl));
178 context.Response.Redirect (login.ToString (), false);