Search code examples
ruby-on-railsauthenticationpuma

Rails: How to add HTTP AUTH at custom action


How to add HTTP AUTH at custom controller action?

class MyController < ApplicationController
  def index
    #NO AUTH
  end

  def custom
    #I NEED HTTP AUTH ONLY HERE
  end
end

routes.rb:

get 'my/custom', to: 'my#custom'

Solution

  • class MyController < ApplicationController
      http_basic_authenticate_with name: "dhh", password: "secret", only: [:custom]
    
      def custom
        #I NEED HTTP AUTH ONLY HERE
      end
    end
    

    You can also call the auth directly in the action:

    class MyController < ApplicationController
      def custom
        authenticate_or_request_with_http_basic do |username, password|
          username == "dhh" && password == "secret"
        end
    
        ...
      end
    end
    

    Here are the docs for more advanced usage: https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html