FormsAuthenticationModule.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. //
  2. // System.Web.Security.FormsAuthenticationModule
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Security.Principal;
  11. using System.Web;
  12. using System.Web.Configuration;
  13. namespace System.Web.Security
  14. {
  15. public sealed class FormsAuthenticationModule : IHttpModule
  16. {
  17. bool noForms;
  18. public void Dispose ()
  19. {
  20. }
  21. public void Init (HttpApplication app)
  22. {
  23. app.AuthenticateRequest += new EventHandler (OnAuthenticateRequest);
  24. app.EndRequest += new EventHandler (OnEndRequest);
  25. }
  26. void OnAuthenticateRequest (object sender, EventArgs args)
  27. {
  28. HttpApplication app = (HttpApplication) sender;
  29. HttpContext context = app.Context;
  30. AuthConfig config = (AuthConfig) context.GetConfig ("system.web/authentication");
  31. if (config.Mode != AuthenticationMode.Forms) {
  32. noForms = true;
  33. return;
  34. }
  35. string cookieName = config.CookieName;
  36. string cookiePath = config.CookiePath;
  37. string loginPage = config.LoginUrl;
  38. FormsAuthenticationEventArgs formArgs = new FormsAuthenticationEventArgs (context);
  39. if (Authenticate != null)
  40. Authenticate (this, formArgs);
  41. bool contextUserNull = (context.User == null);
  42. if (formArgs.User != null || !contextUserNull) {
  43. if (contextUserNull)
  44. context.User = formArgs.User;
  45. return;
  46. }
  47. HttpCookie cookie = context.Request.Cookies [cookieName];
  48. if (cookie == null || (cookie.Expires != DateTime.MinValue && cookie.Expires < DateTime.Now)) {
  49. return;
  50. }
  51. FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt (cookie.Value);
  52. FormsAuthentication.RenewTicketIfOld (ticket);
  53. context.User = new GenericPrincipal (new FormsIdentity (ticket), new string [0]);
  54. cookie.Value = FormsAuthentication.Encrypt (ticket);
  55. cookie.Path = cookiePath;
  56. if (ticket.IsPersistent)
  57. cookie.Expires = ticket.Expiration;
  58. context.Response.Cookies.Add (cookie);
  59. context.SkipAuthorization = (context.Request.Path == loginPage);
  60. }
  61. void OnEndRequest (object sender, EventArgs args)
  62. {
  63. if (noForms)
  64. return;
  65. HttpApplication app = (HttpApplication) sender;
  66. HttpContext context = app.Context;
  67. if (context.Response.StatusCode != 401)
  68. return;
  69. AuthConfig config = (AuthConfig) context.GetConfig ("system.web/authentication");
  70. context.Response.Redirect (config.LoginUrl);
  71. }
  72. public event FormsAuthenticationEventHandler Authenticate;
  73. }
  74. }