Grape的API密钥身份验证

忍者男孩

我有我的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密钥身份验证模型中对请求进行身份验证。

请帮忙。

布罗佐雷克

定义您的代码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 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章