使用authlogic_api进行Rails REST API访问

zin*_*ign 7 ruby security rest ruby-on-rails authlogic

我正在为只能通过REST调用访问的Steam游戏编写Rails后端API,因此不需要特定于用户的身份验证.我正在尝试为Authlogic gem 实现authlogic_api插件,该插件使用api_key/signature机制来限制访问.我已经实现了rdocs中概述的ApplicationSessionApplicationAccount模型,但我不确定如何修改我的ApplicationController以限制访问.

查看源代码,authlogic_api插件似乎修改了Authlogic中的ActsAsAuthenticSession模块.但由于这实际上是"单一访问"身份验证,要求在每次请求时传递API密钥和签名,我不会看到会话如何成为一个因素.

有没有人在他们的应用程序中成功实现了authlogic_api?如果是这样,您会分享设置ApplicationController的方法吗?

Dav*_*e T 4

事实上,这要简单得多。使用 Authlogic 示例中的所有代码有点矫枉过正 - 它主要管理存储会话详细信息,而您不需要为应用程序(也称为客户端)会话执行此操作。每次请求时都会重新确认客户端会话。

所有你需要的是:

模型\client.rb

class Client < ActiveRecord::Base
  acts_as_authentic do |config|
  end
end
Run Code Online (Sandbox Code Playgroud)

模型\client_session.rb

class ClientSession < Authlogic::Session::Base
  api_key_param 'app_key'
end
Run Code Online (Sandbox Code Playgroud)

控制器\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
Run Code Online (Sandbox Code Playgroud)

您还需要运行迁移来创建客户端表。并非下面的所有字段都是必需的,但它们不会有什么坏处。

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
Run Code Online (Sandbox Code Playgroud)