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
广告