使用rails-api的基本身份验证

tha*_*way 18 ruby-on-rails basic-authentication ruby-on-rails-3

我确定我在这里做错了,但这就是我的应用程序控制器的样子:

class ApplicationController < ActionController::API                                                                                                                                                                                                        
  include ActionController::HttpAuthentication::Basic                                                                                                                                                                                                      
  include ActionController::MimeResponds                                                                                                                                                                                                                   

  http_basic_authenticate_with :name => "joeyjojo", :password => "shabadoo"
end
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么我的http_basic_authenticate_with会抛出此错误:

undefined method `http_basic_authenticate_with' for ApplicationController:Class
Run Code Online (Sandbox Code Playgroud)

我确定这很简单,但我没有看到它.MimeResponds在其他控制器中工作得很好.

小智 22

您必须包含ActionController::HttpAuthentication::Basic::ControllerMethods,以使方法可用.这是模块中的ActionController::Base


Fer*_*ara 9

如果您有Rails API,请将其添加到您的控制器:

包括ActionController :: HttpAuthentication :: Basic :: ControllerMethods

class YourController < ApplicationController

  include ActionController::HttpAuthentication::Basic::ControllerMethods
  http_basic_authenticate_with name: "username", password: "passwd123"
Run Code Online (Sandbox Code Playgroud)

我正在使用Rails 4.2.4和我的ApplicationController:

class ApplicationController < ActionController::API
Run Code Online (Sandbox Code Playgroud)