create a http server and parse authorization headers in csharp

Here's an example of how to create a simple HTTP server in C# that parses authorization headers:

main.cs
using System;
using System.Net;
using System.Text;

class HttpServer 
{
    private HttpListener listener;

    public HttpServer(string host, int port)
    {
        listener = new HttpListener();
        listener.Prefixes.Add($"http://{host}:{port}/");
        listener.Start();
        Console.WriteLine($"HTTP server listening on {host}:{port}");
    }

    public void Run()
    {
        while (true) 
        {
            HttpListenerContext context = listener.GetContext();
            HttpListenerRequest request = context.Request;
            HttpListenerResponse response = context.Response;

            if (request.Headers["Authorization"] != null) 
            {
                var authHeader = request.Headers["Authorization"];
                var authHeaderArr = authHeader.Split(' ');
                
                if (authHeaderArr.Length == 2 && authHeaderArr[0] == "Basic")
                {
                    var credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeaderArr[1]));
                    var credentialArr = credentials.Split(':');
                    var username = credentialArr[0];
                    var password = credentialArr[1];
                    Console.WriteLine($"Received valid credentials: username={username}, password={password}");
                }
                else 
                {
                    Console.WriteLine($"Invalid Authorization header format: {authHeader}");
                }
            }

            string responseString = "<html><body><p>Hello, world!</p></body></html>";
            byte[] buffer = Encoding.UTF8.GetBytes(responseString);
            response.ContentLength64 = buffer.Length;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.Close();
        }
    }
}

class Program 
{
    static void Main(string[] args) 
    {
        var server = new HttpServer("localhost", 8000);
        server.Run();
    }
}
1961 chars
61 lines

This code creates an HTTP server listening on localhost:8000. When a client connects to the server and sends a request, it checks the Authorization header for Basic authentication. If the header is in the proper format, it extracts the username and password from the header and logs it to the console. Regardless of whether authorization is successful or not, the server always responds with a simple HTML message.

Note that this is just a basic example, and in practice, you would want to add additional security measures and error handling.

gistlibby LogSnag