Ruby on Rails 2.1 - HTTP 基本認證



Rails 提供了多種實現身份驗證和授權的方法。但最簡單的一種是在 Rails 2.0 中新增的新模組。此模組是透過 SSL 進行 API 身份驗證的好方法。

要使用此身份驗證,您需要使用 SSL 進行流量傳輸。在本教程中,我們將不使用 SSL 進行測試。

讓我們從我們在整個教程中討論的庫示例開始。要實現身份驗證,我們不需要做太多事情。我們將在 **~library/app/controllers/book_controller.rb** 中新增幾行藍色程式碼:

最終,您的 **book_controller.rb** 檔案將如下所示:

class BookController < ApplicationController

USER_ID, PASSWORD = "zara", "pass123"
 
# Require authentication only for edit and delete operation
   before_filter :authenticate, :only => [ :edit, :delete ]
  
def list
   @books = Book.find(:all)
end
   
def show
   @book = Book.find(params[:id])
end
   
def new
   @book = Book.new
   @subjects = Subject.find(:all)
end
   
def create
   @book = Book.new(params[:book])
   if @book.save
      redirect_to :action => 'list'
   else
      @subjects = Subject.find(:all)
      render :action => 'new'
   end
end
   
def edit
   @book = Book.find(params[:id])
   @subjects = Subject.find(:all)
end
   
def update
   @book = Book.find(params[:id])
   if @book.update_attributes(params[:book])
      redirect_to :action => 'show', :id => @book
   else
      @subjects = Subject.find(:all)
      render :action => 'edit'
   end
end
   
def delete
   Book.find(params[:id]).destroy
   redirect_to :action => 'list'
end
   
def show_subjects
   @subject = Subject.find(params[:id])
end
   
private
   def authenticate
      authenticate_or_request_with_http_basic do |id, password| 
         id == USER_ID && password == PASSWORD
      end
   end
end

讓我們解釋一下這些新行:

  • 第一行只是定義訪問各個頁面的使用者 ID 和密碼。

  • 在第二行中,我們使用了 before_filter,它用於在控制器中的任何操作之前執行配置的方法 authenticate。可以透過宣告要包含或排除的操作來將過濾器限制在特定操作上。這兩個選項都接受單個操作(:only => :index)或運算元組(:except => [:foo, :bar])。因此,這裡我們僅對編輯和刪除操作進行了身份驗證。

  • 由於第二行,每當您嘗試編輯或刪除圖書記錄時,它都會執行私有 authenticate 方法。

  • 私有 authenticate 方法正在呼叫 uthenticate_or_request_with_http_basic 方法,該方法包含一個程式碼塊並顯示一個對話方塊以詢問使用者 ID 和密碼以繼續。如果您輸入正確的使用者 ID 和密碼,則會繼續,否則會顯示“訪問被拒絕”。

現在,嘗試編輯或刪除任何可用的記錄,為此您需要透過以下對話方塊進行身份驗證過程。

Http Basic Authentication
廣告