Added BasicAuth, HostName Server, HTTPS (Maybe)

This commit is contained in:
Michael Nolan
2022-04-03 09:39:54 -05:00
parent 937a2e15c6
commit dc581343a4
6 changed files with 419 additions and 51 deletions
+229 -19
View File
@@ -9,6 +9,8 @@ using System.Collections.Generic;
using System.Linq;
using HeyRed.Mime;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace Tesses.WebServer
{
@@ -64,6 +66,20 @@ namespace Tesses.WebServer
{
return args[key][0];
}
public static bool TryGetFirst<T1,T2>(this Dictionary<T1,List<T2>> args,T1 key,out T2 value)
{
List<T2> ls;
if (args.TryGetValue(key,out ls))
{
if(ls.Count > 0)
{
value = ls[0];
return true;
}
}
value = default(T2);
return false;
}
public static void Add<T1,T2>(this Dictionary<T1,List<T2>> list,T1 key,T2 item)
{
if (list.ContainsKey(key))
@@ -178,6 +194,16 @@ namespace Tesses.WebServer
}
public abstract class Server : IServer
{
public static readonly NotFoundServer ServerNull = new NotFoundServer();
public IServer Guaranteed(IServer svr)
{
if(svr != null)
{
return svr;
}
return ServerNull;
}
public bool CorsHeader = true;
public abstract Task GetAsync(ServerContext ctx);
public virtual async Task PostAsync(ServerContext ctx)
@@ -199,17 +225,21 @@ namespace Tesses.WebServer
}
public virtual async Task<bool> BeforeAsync(ServerContext ctx)
{
if(CorsHeader)
{
ctx.ResponseHeaders.Add("Access-Control-Allow-Origin", "*");
ctx.ResponseHeaders.Add("Access-Control-Allow-Headers", "Cache-Control, Pragma, Accept, Origin, Authorization, Content-Type, X-Requested-With");
ctx.ResponseHeaders.Add("Access-Control-Allow-Methods", "GET, POST");
ctx.ResponseHeaders.Add("Access-Control-Allow-Credentials", "true");
}
return await Task.FromResult(false);
}
public void AddCors(ServerContext ctx)
{
if (CorsHeader)
{
ctx.ResponseHeaders.Add("Access-Control-Allow-Origin", "*");
ctx.ResponseHeaders.Add("Access-Control-Allow-Headers", "Cache-Control, Pragma, Accept, Origin, Authorization, Content-Type, X-Requested-With");
ctx.ResponseHeaders.Add("Access-Control-Allow-Methods", "GET, POST");
ctx.ResponseHeaders.Add("Access-Control-Allow-Credentials", "true");
}
}
}
public sealed class MountableServer : Server
@@ -220,21 +250,23 @@ namespace Tesses.WebServer
_root = root;
}
IServer _root;
private KeyValuePair<string,IServer> GetFromPath(ServerContext ctx)
private (string Key,IServer Value) GetFromPath(ServerContext ctx)
{
//bool j = false;
foreach(var item in _servers.Reverse())
{
if(ctx.UrlPath.StartsWith(item.Key,StringComparison.Ordinal))
{
return item;
return (item.Key,Guaranteed(item.Value));
}
if (ctx.UrlPath == item.Key.TrimEnd('/'))
{
ctx.UrlPath += "/";
return (item.Key,Guaranteed(item.Value));
}
}
Console.WriteLine("HERE WE ARE");
return new KeyValuePair<string, IServer>("/",_root);
//Console.WriteLine("HERE WE ARE");
return ("/",Guaranteed(_root));
}
/// <summary>
/// Mount the specified url and server.
@@ -305,9 +337,150 @@ namespace Tesses.WebServer
await v.Value.OtherAsync(ctx);
}
}
public delegate bool Authenticate(string username, string password);
public class BasicAuthServer : Server
{
public BasicAuthServer(Authenticate auth,IServer inner,string realm="SampleRealm")
{
Authenticate = auth;
InnerServer = inner;
Realm = realm;
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
if(await Authorize(ctx))
{
return await Guaranteed(InnerServer).BeforeAsync(ctx);
}
return true;
}
public override async Task GetAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).GetAsync(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).PostAsync(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).OtherAsync(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
await Guaranteed(InnerServer).OptionsAsync(ctx);
}
public IServer InnerServer { get; set; }
public Authenticate Authenticate { get; set; }
public string Realm { get; set; }
private bool ValidAuth(ServerContext ctx)
{
string auth;
if (ctx.RequestHeaders.TryGetFirst("Authorization", out auth))
{
string[] authorization = auth.Split(' ');
//authorization_basic
if (authorization[0] == "Basic")
{
string[] userPass = Encoding.UTF8.GetString(Convert.FromBase64String(authorization[1])).Split(new char[] { ':' },2);
//return userPass.Equals($"{config.UserName}:{config.Password}", StringComparison.Ordinal);
return Authenticate(userPass[0], userPass[1]);
}
}
return false;
}
private async Task<bool> Authorize(ServerContext ctx)
{
if (Authenticate == null)
return true;
if (ValidAuth(ctx))
return true;
ctx.ResponseHeaders.Add("WWW-Authenticate", $"Basic realm=\"{Realm}\"");
ctx.StatusCode = 401;
await UnauthorizedPage(ctx);
return false;
}
protected virtual async Task UnauthorizedPage(ServerContext ctx)
{
await ctx.SendTextAsync("Unauthorized");
}
}
public class HostDomainServer : Server
{
public HostDomainServer(IServer alt)
{
Default = alt;
Servers = new Dictionary<string, IServer>();
}
public void Clear()
{
Servers.Clear();
}
public void Remove(string fqdn_or_ip)
{
Servers.Remove(fqdn_or_ip);
}
public IServer Default { get; set; }
Dictionary<string, IServer> Servers;
public void AddDomain(string fqdn_or_ip,IServer svr)
{
Servers.Add(fqdn_or_ip, svr);
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
return await GetDomain(ctx).BeforeAsync(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
await GetDomain(ctx).PostAsync(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
await GetDomain(ctx).OtherAsync(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
await GetDomain(ctx).OptionsAsync(ctx);
}
public override async Task GetAsync(ServerContext ctx)
{
await GetDomain(ctx).GetAsync(ctx);
}
private IServer GetDomain(ServerContext ctx)
{
string fqdn_or_ip = ctx.Host;
foreach(var item in Servers)
{
if(item.Key.Equals(fqdn_or_ip,StringComparison.Ordinal))
{
return Guaranteed(item.Value);
}
}
return Guaranteed(Default);
}
}
public interface IServer
{
void AddCors(ServerContext ctx);
Task<bool> BeforeAsync(ServerContext ctx);
Task GetAsync(ServerContext ctx);
Task PostAsync(ServerContext ctx);
@@ -317,14 +490,29 @@ namespace Tesses.WebServer
public sealed class HttpServerListener
{
bool https;
X509Certificate cert;
IServer _server;
TcpListener _listener;
public HttpServerListener(IPEndPoint endPoint,IServer server)
{
_listener = new TcpListener(endPoint);
_server = server;
https = false;
}
public HttpServerListener(IServer server)
{
_listener = new TcpListener(new IPEndPoint(IPAddress.Any, 3251));
_server = server;
https = false;
}
public HttpServerListener(IPEndPoint endpoint,IServer server,X509Certificate cert)
{
_listener = new TcpListener(endpoint);
_server = server;
https = cert != null;
this.cert = cert;
}
public async Task ListenAsync(CancellationToken token)
{
_listener.Start();
@@ -332,12 +520,12 @@ namespace Tesses.WebServer
while (!token.IsCancellationRequested)
{
var socket=await _listener.AcceptTcpClientAsync();
await CommunicateHostAsync(socket);
await CommunicateHostAsync(socket).ConfigureAwait(false);
}
}
}
private string ReadHeaders(NetworkStream strm)
private string ReadHeaders(Stream strm)
{
StringBuilder s = new StringBuilder();
@@ -375,6 +563,25 @@ namespace Tesses.WebServer
}
return items;
}
public Stream GetStream(TcpClient clt)
{
if(https)
{
SslStream sslStream = new SslStream(
clt.GetStream(), false);
try
{
sslStream.AuthenticateAsServer(cert, clientCertificateRequired: false, checkCertificateRevocation: true);
}
catch (Exception ex)
{
_ = ex;
}
return sslStream;
}
return clt.GetStream();
}
private async Task CommunicateHostAsync(TcpClient clt)
{
//<METHOD> <PATH> HTTP/1.1\r\n
@@ -387,7 +594,7 @@ namespace Tesses.WebServer
//RESPONSE
using (NetworkStream strm = clt.GetStream())
using (Stream strm = GetStream(clt))
{
string request_line = "";
@@ -403,6 +610,9 @@ namespace Tesses.WebServer
string path = request[1];
string ver = request[2];
ctx = new ServerContext(method, strm, path, headers);
ctx.Server = clt.Client.LocalEndPoint as IPEndPoint;
ctx.Client = clt.Client.RemoteEndPoint as IPEndPoint;
_server.AddCors(ctx);
if (!await _server.BeforeAsync(ctx))
{
switch (method)