Ruby on Rails 2.1 Basic HTTP Auth - Ruby on Rails 2.1

How to use HTTP Auth on Rails 2.1?

Rails HTTP Auth is awesome way to do API authentication over SSL. Rails have different methods of implementing authentication and authorization. HTTP Auth is the simplest and greatest one among them. This has been released in the version Ruby on rails 2.0

User needs to use SSL to use HTTP Auth authentication, which helps for traffic transportation. Here we are testing it without SSL.

Now, starting with our library example, add few lines in blue in ~library/app/controllers/book_controller.rb:

Once done adding lines, book_controller.rb file looks as below

Let’s have a look at the lines added

  • First line is to define user ID and password to access different pages.
  • Second one, before_filter which is used to run the configured method authenticate before any action in the controller. A filter may be limited to specific actions by declaring the actions to include or exclude. Both options accept single actions (:only => :index) or arrays of actions (:except => [:foo, :bar]). So here we have put authentication for edit and delete operations only.
  • As a result, whenever user tries to edit or delete a book record, it will execute private authenticate method.
  • Private authenticate method is callingauthenticate_or_request_with_http_basic method, that comprises of a block and displays a dialogue box to ask for User ID and Password to proceed. If user enters a correct user ID and password, it will proceed else displays access denied.

To do the authentication process let’s edit or delete any available record using below dialogue box.

user-authentication-box

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Ruby on Rails 2.1 Topics