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和密码,则将继续,否则将显示"访问被拒绝"。
现在,尝试编辑或删除任何可用记录,为此,您必须使用以下对话框完成身份验证过程。