加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 无法访问http_basic块中的任何Grape :: API方

发布时间:2020-12-17 03:01:20 所属栏目:百科 来源:网络整理
导读:我使用 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 @cur
我使用 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

似乎我无法访问http_basic块中的任何方法或对象,包括请求,env,帮助器方法中的任何内容,甚至没有错误!

看一下代码,这没有意义.

有没有人遇到过这个?有没有人有任何使用带有http基本身份验证的Grape API的例子?网络上的例子不是现实世界的例子.

解决方法

Grape将您的http_basic块存储为其设置哈希中的proc. Grape :: API中的build_endpoint方法汇集了所有这些:

Rack::Builder.new.use Rack::Auth::Basic,"API Authorization",&your_block

此时您的助手不可用. (见https://github.com/intridea/grape/blob/master/lib/grape/api.rb#L258)

您可以尝试在没有帮助程序的情况下实现此操作,方法是在User模型中使用类方法,如下所示:

http_basic do |user,password|
  User.authenticate(user,password)
end

如果用户也不可用,请使用上面一行中的Rack :: Builder实现您自己的基本身份验证.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读