Rack comes with a fair bit of built-in middleware that you can use to put together a simple app frame. Unfortunately, Rack authentication’s documentation is pretty bad, so let’s see some simple, self-explanatory examples, shall we?
We’ll need a config.ru file for this, and you’ll need Rack installed. Here’s how you want config.ru to look, at the beginning:
1 2 3 4 5 6 7 8 9
This is as simple as Rack apps get. Return success (200), a content-type header that says it’s text, and “Hello, World!” — which has to be in a list because Rack says so.
What’s the easiest way to put a password in front of this?
Rack comes with nice simple built-in authentication modules. Here’s how you use the Basic auth middleware:
1 2 3 4 5 6 7 8 9 10 11 12
The “use” statement says to include the password middleware. You can see that the password is “secret” with any user, so type “secret” as the password in your browser! Just return true if they pass the check or false otherwise.
You can also use Digest authentication with Rack::Auth::Digest::MD5. It wants to pass you the username and have you return the password, which it hashes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
That looks the same to you… But it doesn’t send your password in the clear!
Notice that you have to set an “opaque” — that’s a long secret key which should always be the same for your app. I’d recommend you randomize it, not use “1234567890” :–)
These are the only authentication methods Rack supports. That makes sense — they’re the only authentication methods that most browsers support properly.
Now that you have some decent examples, go forth and authenticate your Rack applications!
What Rack applications? That’s anything with Rails, Sinatra or your framework of choice, of course!
If you like playing down in the Rack internals, have I mentioned that I’m writing a book called “Rebuilding Rails” about that?