ruby-on-rails – Rails 4.2中未定义的方法’authenticate_with_http_basic’

我正在尝试使用Devise来验证服务器端API.在我的控制器中,我直接使用Devise wiki中的代码来了解如何使用HTTP Basic auth …
before_filter :check_auth,only: [:show]

def check_auth
    authenticate_or_request_with_http_basic do |username,password|
      resource = User.find_by_email(username)
      if resource.valid_password?(password)
        sign_in :user,resource
      end
    end
  end

当我转到预期的URL时,我期望401 Unauthorized JSON错误,但是,我得到以下错误

undefined method `authenticate_or_request_with_http_basic' for #<V1::ItemsController:0x007fb6b3d79120>

我不明白为什么不定义这种方法.我正在使用Rubymine并且IDE直接链接到该方法代码,但由于某种原因出了问题.任何人都可以帮我弄清楚我做错了什么?

更新:我能够确定我的问题.我正在使用Rails-API与完整的Rails,因此HttpAuthentication的模块(令人惊讶地)不包括在内.

通过增加

include ActionController::HttpAuthentication::Basic::ControllerMethods

到我的ApplicationController,它现在按预期工作.

解决方法

这是因为Rails API是基础Rails库的子集,并且认情况下不包括处理authenticate_with_http_basic方法的模块.您需要在application_controller.rb中包含这些模块.

应用程序/控制器/ application_controller.rb

include ActionController::HttpAuthentication::Basic::ControllerMethods
include ActionController::HttpAuthentication::Token::ControllerMethods

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...