Jam*_*ght 4 ruby gem ruby-on-rails
我正在使用Grape gem为我的应用程序创建API.一切都运行良好,直到我将http基本身份验证添加到我的api中,该api内置于Grape api中.
这是我的代码:
require 'grape'
module MyApp
class API < Grape::API
prefix 'api'
version 'v1'
helpers do
def current_user
@current_user ||= User.authenticate(env)
end
def authenticate!
error!('401 Unauthorized', 401) unless current_user
end
end
resources :projects do
http_basic do |u,p|
authenticate! #=> Results in undefined method `authenticate!' for MyApp::API:Class (NoMethodError)
error! "401 Unauthorized", 401
!current_user.nil?
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
似乎我无法访问http_basic块中的任何方法或对象,包括请求,env,帮助器方法中的任何内容,甚至没有错误!
看一下代码,这没有意义.
有没有人遇到过这个?有没有人有任何使用带有http基本身份验证的Grape API的例子?网络上的例子不是现实世界的例子.
Grape将您的http_basic块存储为其设置哈希中的proc.该build_endpoint方法Grape::API汇集了所有这些:
Rack::Builder.new.use Rack::Auth::Basic, "API Authorization", &your_block
Run Code Online (Sandbox Code Playgroud)
此时您的助手不可用.(见https://github.com/intridea/grape/blob/master/lib/grape/api.rb#L258)
您可以尝试在没有帮助程序的情况下实现此操作,方法是在User模型中使用类方法,如下所示:
http_basic do |user, password|
User.authenticate(user, password)
end
Run Code Online (Sandbox Code Playgroud)
如果User也不可用,请使用Rack::Builder上面的行中的like来实现您自己的基本身份验证.