Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using authlogic_api for Rails REST API access

I am writing a Rails back-end API for a Steam game that is only accessed via REST calls, so no user-specific authentication is required. I am trying to implement the authlogic_api plug-in for the Authlogic gem, which uses an api_key/signature mechanism to restrict access. I have implemented the ApplicationSession and ApplicationAccount models as outlined in the rdocs, but I'm not sure how to modify my ApplicationController to restrict access.

Looking at the source, it appears the authlogic_api plug-in modifies the ActsAsAuthentic and Session modules from Authlogic. But since this is essentially "single access" authentication, requiring the API key and signature to be passed on every request, I don't see how sessions would be a factor.

Has anyone successfully implemented authlogic_api in their apps? If so, would you share your approach for setting up your ApplicationController?

like image 511
zinndesign Avatar asked Jun 24 '10 16:06

zinndesign


1 Answers

Actually, it's much simpler. Using all that code from the Authlogic example is somewhat overkill - it mainly manages storing session details, which you don't need to do for the Application (also known as Client) session. The Client session is re-confirmed at every request.

All you need is:

models\client.rb

class Client < ActiveRecord::Base
  acts_as_authentic do |config|
  end
end

models\client_session.rb

class ClientSession < Authlogic::Session::Base
  api_key_param 'app_key'
end

controllers\application_controller

before_filter :verify_client

def verify_client
  @client_session = ClientSession.new()
  unless @client_session.save # if client session not successfully created using the api_key and signature, render an error and block the request
    @error = {:description => "Couldn't validate client application."}
    render :template => 'errors/error.xml.builder'
  end
end

You also need to run a migration to create the clients table. Not all of the fields below are necessary, but they won't hurt.

class CreateClients < ActiveRecord::Migration
  def self.up
    create_table :clients do |t|
      # human fields
      t.string :name
      t.string :owner
      t.string :owner_email
      t.string :owner_phone
      # login fields
      t.string :api_key, :null => false
      t.string :api_secret, :null => false
      t.string :password_salt
      t.string :persistence_token
      t.string :perishable_token
      # automagical fields (courtesy of authlogic & authlogic_api)
      t.integer :failed_login_count
      t.datetime :last_request_at
      t.integer :request_count
      t.string :last_request_ip
      # automagical fields (courtesy of rails)
      t.timestamps
    end
  end

  def self.down
    drop_table :clients
  end
end
like image 160
Dave T Avatar answered Oct 05 '22 23:10

Dave T