Clearance::HttpAuth¶ ↑
The goal of this project is simple, instant HTTP Basic Authentication for any controller in Rails 3 applications using Clearance for user authentication. You can use Clearance’s default, session based authentication in the user facing parts of your application, and use HTTP Basic Auth when connecting to it’s API.
It has two parts:
-
A middleware which intercepts requests to your application API and performs a HTTP Basic Authentication by wrapping your application in a
Rack::Auth::Basic
block. It supplies the provided credentials to theUser.authenticate
method and sets anenv['clearance.current_user']
variable. -
An overriden
current_user
helper method for controllers, which reads the variable set in the middleware.
Usage¶ ↑
First, add the gem to your Gemfile, along with clearance
:
gem 'clearance', '~> 0.9.1' gem 'clearance_http_auth'
Second, include the module in your ApplicationController (or in a specific controller) after you include Clearance::Authentication:
class ApplicationController < ActionController::Base include Clearance::Authentication include Clearance::HttpAuth end
There is no step three. When you hit your application API with the same credentials as when logging in the browser, you should be in:
$ curl -i -X GET -u test@example.com:password http://localhost:3000/books.xml $ curl -i -X POST -u test@example.com:password -H "Content-Type: application/xml" http://localhost:3000/books.xml \ -d "<book><author>Kafka</author><title>Metamorphosis</title></book>"
By default, the middleware intercepts only requests to JSON and XML formats. You can add more formats in your config/application.rb
:
config.clearance_http_auth.api_formats << 'csv'
About¶ ↑
The project originally grew out of a simple monkeypatch: github.com/thoughtbot/clearance/issues/34
Comments and patches are welcome. Fork, add tests for features and don’t break any existing ones, send a pull request.
Karel Minarik (karmi.cz)