22
votes

I'm sure that I'm doing something wrong here, but this is what my application controller looks like:

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

  http_basic_authenticate_with :name => "joeyjojo", :password => "shabadoo"
end

I can't figure out why my http_basic_authenticate_with is throwing this error:

undefined method `http_basic_authenticate_with' for ApplicationController:Class

I'm sure it's something simple, but I don't see it. The MimeResponds is working just fine in other controllers.

2
Why you applicationcontroller inherited from actioncontroller::api?Mikhail Nikalyukin
This is using the rails-api gemthatmiddleway

2 Answers

27
votes

You have to include ActionController::HttpAuthentication::Basic::ControllerMethods instead, to have the methods available. Here's the module in ActionController::Base

14
votes

If you have a Rails API, add this to your controller:

include ActionController::HttpAuthentication::Basic::ControllerMethods

class YourController < ApplicationController

  include ActionController::HttpAuthentication::Basic::ControllerMethods
  http_basic_authenticate_with name: "username", password: "passwd123"

I am using Rails 4.2.4 and my ApplicationController:

class ApplicationController < ActionController::API