Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined method 'authenticate_with_http_basic' in Rails 4.2

I'm trying to use Devise to authenticate a server-side API. In my controller, I'm using the code straight out of the Devise wiki for how to use HTTP Basic auth...

   before_filter :check_auth, only: [:show] 

and

  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

When I go to the intended URL, I expect a 401 Unauthorized JSON error, however, instead I get the following error:

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

I don't understand why that method wouldn't be defined. I'm using RubyMine and the IDE links straight to the code for that method, but for some reason something is wrong. Can anyone help me figure out what I'm doing wrong?

UPDATE: I was able to identify my issue. I'm using Rails-API vs. full Rails so the module for HttpAuthentication is (surprisingly) not included.

By adding:

include ActionController::HttpAuthentication::Basic::ControllerMethods

to my ApplicationController, it is now working as intended.

like image 984
user3144632 Avatar asked Jun 26 '15 20:06

user3144632


1 Answers

That’s because Rails API is a subset of the base Rails library, and by default doesn’t include the modules to handle the authenticate_with_http_basic method. You’ll need to include these modules in your application_controller.rb.

app/controllers/application_controller.rb

include ActionController::HttpAuthentication::Basic::ControllerMethods
include ActionController::HttpAuthentication::Token::ControllerMethods
like image 112
jordancolbycox Avatar answered Nov 19 '22 04:11

jordancolbycox