August 10th, 2009

HTTP Auth for Clearance plugin for Rails

I needed HTTP authentication for API requests on a current project, which uses Clearance as a authentication layer, and discovered Clearance does not provide any.

You can use the following patch if you’d need it as well.

If you think Clearance should provide HTTP-Auth out-of-the-box, vote on this issue at Github, thanks!

# Overload Clearance's `deny_access` methods to allow authentication with HTTP-Auth for eg. API access
# Modeled after technoweenie's restful_authentication
#
# In lib/clearance_http_auth.rb
module Clearance
  module Authentication
 
    module InstanceMethods
      
      def deny_access(flash_message = nil, opts = {})
        store_location
        flash[:failure] = flash_message if flash_message
        respond_to do |format|
          format.html { redirect_to new_session_url }
          format.any(:json, :xml) do
            authenticate_or_request_with_http_basic('My app API') do |login, password|
              @_current_user = ::User.authenticate(login, password)
            end
          end
        end
      end
 
    end
 
  end
end
view raw This Gist brought to you by GitHub.
blog comments powered by Disqus