Imagine you have a staging server or admin area, and you want to allow certain IP addresses unconditional access, but require visitors from others to provide credentials to get access. Here’s a neat and useful little middleware I just threw together that allows exactly this. Even better, it uses code that’s already available in rack and rack-contrib. Here’s how to do it:

The code:

Then, you just need to insert it into your middleware, and provide the routes to restrict, and what IP addresses can access them. The following blocks everything that’s not a local request, and requires authentication for everyone else: