Skip to content

Instantly share code, notes, and snippets.

@dschenkelman
Created May 9, 2014 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dschenkelman/7c3b4abaa741d53c8a6c to your computer and use it in GitHub Desktop.
Save dschenkelman/7c3b4abaa741d53c8a6c to your computer and use it in GitHub Desktop.
Intro to OWIN talk and a simple IP filtering middleware sample
namespace Owin.IpFilter
{
using System;
using System.Net;
public static class Extensions
{
public static IAppBuilder UseIpFiltering(this IAppBuilder appBuilder, Func<IPAddress, bool> rejectRequest)
{
appBuilder.Use(typeof(IpFilterMiddleware), rejectRequest);
return appBuilder;
}
}
}
namespace Owin.IpFilter
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;
public class IpFilterMiddleware
{
private const string Html404 = "<!doctype html><html><head><meta charset=\"utf-8\"><title>404 Not Found</title></head><body>The resource cannot be found.</body>" + "</html>";
private readonly AppFunc nextMiddleware;
private readonly Func<IPAddress, bool> rejectRequest;
public IpFilterMiddleware(AppFunc nextMiddleware, Func<IPAddress, bool> rejectRequest)
{
if (nextMiddleware == null)
{
throw new ArgumentNullException("nextMiddleware");
}
this.nextMiddleware = nextMiddleware;
this.rejectRequest = rejectRequest;
}
public Task Invoke(IDictionary<string, object> environment)
{
var remoteAddress = IPAddress.Parse((string)environment["server.RemoteIpAddress"]).MapToIPv4();
if (this.rejectRequest(remoteAddress))
{
var responseStream = (Stream)environment["owin.ResponseBody"];
var responseHeaders =
(IDictionary<string, string[]>)environment["owin.ResponseHeaders"];
var responseBytes = Encoding.UTF8.GetBytes(Html404);
responseHeaders["Content-Type"] = new[] { "text/html" };
responseHeaders["Content-Length"] = new[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
environment["owin.ResponseStatusCode"] = 404;
return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
return this.nextMiddleware(environment);
}
}
}
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder.UseIpFiltering(
remoteAddress =>
{
var bytes = remoteAddress.GetAddressBytes();
return bytes[0] != 192 && bytes[0] != 172 && bytes[0] != 10 && bytes[0] != 127 && bytes[0] != 0;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment