Guest User

my last dev

a guest
Feb 15th, 2017
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. /*
  2. * This is my last dev, which is a module to auth user by base windows auth using 401 request
  3. */
  4.  
  5.    public class Module : IHttpModule
  6.     {
  7.         private static readonly List<string> AuthList = new List<string>();
  8.         #region IHttpModule Implements
  9.         public void Init(HttpApplication context)
  10.         {
  11.             context.BeginRequest += AddRequestHeaders;
  12.             context.BeginRequest += CheckAuthentication;
  13.         }
  14.  
  15.         public void Dispose()
  16.         {
  17.             //empty
  18.         }
  19.         #endregion
  20.  
  21.         #region Misc Functions
  22.  
  23.         private void AddRequestHeaders(object sender, EventArgs e)
  24.         {
  25.             var app = (HttpApplication) sender;
  26.             app.Context.Response.AddHeader("X-MyModuleAuth", "true");
  27.         }
  28.  
  29.         private void CheckAuthentication(object sender, EventArgs e)
  30.         {
  31.             var app = (HttpApplication) sender;
  32.  
  33.             var authHeader = app.Context.Request.Headers["Authorization"];
  34.             if (AuthList.Contains(authHeader)) return;
  35.             if (authHeader != null && authHeader.StartsWith("Basic"))
  36.             {
  37.                 var encodeId = authHeader.Substring("Basic ".Length).Trim();
  38.                 var encoding = Encoding.GetEncoding("iso-8859-1");
  39.                 var strId = encoding.GetString(Convert.FromBase64String((encodeId)));
  40.  
  41.                 var sep = strId.IndexOf(':');
  42.                 var user = strId.Substring(0, sep);
  43.                 var pass = strId.Substring(sep + 1);
  44.  
  45.                 try
  46.                 {
  47.                     var usr = FTELNASAuthentication.ValidateUser(user, pass);
  48.                     if (usr != null)
  49.                     {
  50.                         AuthList.Add(authHeader);
  51.                         return;
  52.                     }
  53.                        
  54.                 }
  55.                 catch (Exception ex)
  56.                 {
  57.                     //empty for the moment.
  58.                 }
  59.  
  60.             }
  61.             app.Context.Response.Headers["WWW-Authenticate"] = "Basic";
  62.             app.Context.Response.StatusCode = 401;
  63.             app.CompleteRequest();
  64.         }
  65.         #endregion
  66.  
  67.     }
Add Comment
Please, Sign In to add comment