Ruby on Rails——一个简单的认证

我们建立了一个blog,并且加入了comment功能,但是现在我们发现谁都可以访问它,任何人都有CRUD的权限。现在,我们通过一个简单的示例来学习一下怎么添加权限认证。当然,Rails提供了许多关于认证的内容,实际项目中要比现在的示例复杂一些。

Rails提供了一个简单的http认证系统,通过http_basic_authenticate_with方法来进行控制。

我们在article_controller.rb加入http_basic_authenticate_with,

class ArticlesController < ApplicationController

 

  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]

 

  def index

    @articles = Article.all

  end

 

  # snippet for brevity

except表示出了index和show之外,访问其他的页面都需要用户名和密码的验证。同样,我们需要把comment_controller.rb修改如下:

class CommentsController < ApplicationController

 

  http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy

 

  def create

    @article = Article.find(params[:article_id])

    # ...

  end

 

  # snippet for brevity

only表示只有在destroy的时候才需要进行用户名和密码的验证。修改之后访问页面如下:

Basic HTTP Authentication Challenge

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章