2 // System.Web.Security.FormsAuthenticationModule
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
11 using System.Security.Principal;
14 using System.Web.Configuration;
15 using System.Web.Util;
17 namespace System.Web.Security
19 public sealed class FormsAuthenticationModule : IHttpModule
23 public void Dispose ()
27 public void Init (HttpApplication app)
29 app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest);
30 app.EndRequest += new EventHandler (OnEndRequest);
33 void OnAuthenticateRequest (object sender, EventArgs args)
35 HttpApplication app = (HttpApplication) sender;
36 HttpContext context = app.Context;
37 AuthConfig config = (AuthConfig) context.GetConfig ("system.web/authentication");
38 if (config.Mode != AuthenticationMode.Forms) {
43 string cookieName = config.CookieName;
44 string cookiePath = config.CookiePath;
45 string loginPage = config.LoginUrl;
47 string appVPath = context.Request.ApplicationPath;
48 string reqPath = context.Request.Path;
49 if (reqPath.StartsWith (appVPath))
50 reqPath = reqPath.Substring (appVPath.Length);
52 context.SkipAuthorization = (reqPath == loginPage);
54 FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context);
55 if (Authenticate != null)
56 Authenticate (this, formArgs);
58 bool contextUserNull = (context.User == null);
59 if (formArgs.User != null || !contextUserNull) {
61 context.User = formArgs.User;
65 HttpCookie cookie = context.Request.Cookies [cookieName];
66 if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now))
69 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt (cookie.Value);
70 FormsAuthentication.RenewTicketIfOld (ticket);
71 context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]);
73 cookie.Value = FormsAuthentication.Encrypt (ticket);
74 cookie.Path = cookiePath;
75 if (ticket.IsPersistent)
76 cookie.Expires = ticket.Expiration;
78 context.Response.Cookies.Add (cookie);
81 void OnEndRequest (object sender, EventArgs args)
86 HttpApplication app = (HttpApplication) sender;
87 HttpContext context = app.Context;
88 if (context.Response.StatusCode != 401 || context.Request.QueryString ["ReturnUrl"] != null)
91 AuthConfig config = (AuthConfig) context.GetConfig ("system.web/authentication");
92 StringBuilder login = new StringBuilder ();
93 login.Append (UrlUtils.Combine (context.Request.ApplicationPath, config.LoginUrl));
94 login.AppendFormat ("?ReturnUrl={0}", HttpUtility.UrlEncode (context.Request.RawUrl));
95 context.Response.Redirect (login.ToString ());
98 public event FormsAuthenticationEventHandler Authenticate;