private static void MaintFace_AuthenticateUser(object sender, AuthEventArgs e) { if (e.User.Identity is HttpListenerBasicIdentity) { // We are using Basic Authentication. // To Do: Check username/password here. e.Authenticated = true; } else if (e.User.Identity is WindowsIdentity) { // Windows Authentication; Can do optional stuff here. e.Authenticated = true; } }
private static async void RunServer(HttpListener listener) { for (;;) { try { var context = await listener.GetContextAsync(); if (context.Request.QueryString["ping"] == "1") { context.Response.Close(); continue; } // Do user u/p check, optional (but necessary for basic auth) if (AuthenticateUser == null) { if(context.User?.Identity is HttpListenerBasicIdentity) { Trace.WriteLine(nameof(MaintFace) + " Warning: Basic Authentication failed; " + nameof(AuthenticateUser) + " event not handled."); context.Response.StatusCode = 401; byte[] message = new UTF8Encoding().GetBytes("Access denied"); context.Response.ContentLength64 = message.Length; context.Response.OutputStream.Write(message, 0, message.Length); context.Response.Close(); continue; } } else { var args = new AuthEventArgs(context.User); AuthenticateUser(null, args); if (args.Authenticated == false) { context.Response.StatusCode = 401; byte[] message = new UTF8Encoding().GetBytes("Access denied"); context.Response.ContentLength64 = message.Length; context.Response.OutputStream.Write(message, 0, message.Length); context.Response.Close(); continue; } } if (!context.Request.IsWebSocketRequest) HandleInitialRequest(context); else HandleWebSocketRequest(context); } catch (Exception ex) { Trace.WriteLine(nameof(MaintFace) + " Error: " + nameof(RunServer) + ": " + ex.Message); // Avoid spinning too fast Thread.Sleep(500); } } }