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

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

发布时间:2020-12-16 23:27:55 所属栏目:百科 来源:网络整理
导读:我正在尝试使用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| res
我正在尝试使用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

(编辑:李大同)

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

    推荐文章
      热点阅读