Grape的API密钥身份验证

时间:2015-12-11 14:09:20

标签: ruby-on-rails ruby api ruby-on-rails-4 grape

我的AuthToken模型

class APIKey < ActiveRecord::Base
  before_create :generate_access_token

  private

  def generate_access_token
    begin
      self.access_token = SecureRandom.hex
    end while self.class.exists?(access_token: access_token)
  end
end

在我的/controllers/api/v1/request.rb

def authenticate!
  token= AuthToken.where(:access_token => params[:token])
  error!('401 Unauthorized', 401) unless token
end

我正在接受像这样的参数

resource :request do
  post :test do
    params do 
     requires :test_param, type: String,
     requires :token, type: String
    end 
    authenticate!
    Email_id.create! # It's handled properly in the controller, There's no problem in it. 
  end 
end

问题是我无法将该特定令牌参数解析为authenticate函数,因此我可以检入模型,然后我可以在API密钥身份验证模型中验证请求。

请帮忙。

1 个答案:

答案 0 :(得分:0)

定义您的authenticate!,以便它需要一个参数:

def authenticate!(token)
  error!('401 Unauthorized', 401) unless AuthToken.where(access_token: token).present?
end

然后从控制器传递出来:

resource :request do
  params do 
   requires :test_param, type: String,
   requires :token, type: String
  end

  post :test do
    authenticate!(params[:token])
  end 
end