Scott Miller
Scott Miller

Reputation: 2308

Is this a reasonable approach for HTTP BASIC authentication with an API key?

I have just begun adding a REST API on a rails app, and since I only wanted to expose a couple controller/actions, I added a method to ApplicationController:

  def http_basic_authentication
    if request.format == Mime::XML
      authenticate_or_request_with_http_basic do |username, api_key|
        self.current_user = User.find(:first, :from => 'users, accounts', :conditions => ["accounts.id = users.account_id AND accounts.api_key = ?", api_key])
      end
    end
  end

Which I can then use with a before_filter on my individual controller/actions that I want to expose. Does anyone have any feedback, code review, or a better approach?

Upvotes: 0

Views: 615

Answers (2)

simianarmy
simianarmy

Reputation: 1507

You may find useful the approach detailed here http://www.compulsivoco.com/2009/05/rails-api-authentication-using-restful-authentication/

This integrates with the common restful_authentication plugin.

Upvotes: 0

Sophie Alpert
Sophie Alpert

Reputation: 143194

Possibly this would be cleaner:

self.current_user = Account.find_by_api_key(api_key).user

Upvotes: 1

Related Questions