Now that we've built an API, we can start thinking about securing it. Both for the users of our web UI and other users that directly hit the API from other sites, authentication is a critical feature that we're missing. We won't build a complete authentication solution, but we'll add the critical authentication middleware that will be the main component in an authentication system. We'll see that it won't be much more work.
We briefly mentioned Rack middleware in Chapter 7, Building an App from the Outside In with Behavior-Driven Development, when we used Rack::Static
to serve static assets. Now we're going to add middleware that will authenticate every request before it hits our app.
First, let's start with a simple example with a file called auth_middleware.rb
:
class AuthMiddleware def initialize(app, opts={}) if ! opts[:secret].is_a?(String) raise ':secret is required' end @app = app @secret = opts[:secret] end ...