use*_*632 8 authentication ruby-on-rails devise
我正在尝试使用Devise来验证服务器端API.在我的控制器中,我直接使用Devise wiki中的代码来了解如何使用HTTP Basic auth ...
before_filter :check_auth, only: [:show]
Run Code Online (Sandbox Code Playgroud)
和
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
Run Code Online (Sandbox Code Playgroud)
当我转到预期的URL时,我期望401 Unauthorized JSON错误,但是,我得到以下错误:
undefined method `authenticate_or_request_with_http_basic' for #<V1::ItemsController:0x007fb6b3d79120>
Run Code Online (Sandbox Code Playgroud)
我不明白为什么不定义这种方法.我正在使用RubyMine并且IDE直接链接到该方法的代码,但由于某种原因出了问题.任何人都可以帮我弄清楚我做错了什么?
更新:我能够确定我的问题.我正在使用Rails-API与完整的Rails,因此HttpAuthentication的模块(令人惊讶地)不包括在内.
通过增加:
include ActionController::HttpAuthentication::Basic::ControllerMethods
Run Code Online (Sandbox Code Playgroud)
到我的ApplicationController,它现在按预期工作.
jor*_*cox 17
这是因为Rails API是基础Rails库的子集,并且默认情况下不包括处理authenticate_with_http_basic方法的模块.您需要在application_controller.rb中包含这些模块.
应用程序/控制器/ application_controller.rb
include ActionController::HttpAuthentication::Basic::ControllerMethods
include ActionController::HttpAuthentication::Token::ControllerMethods
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2369 次 |
| 最近记录: |