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

发布了30 篇原创文章 · 获赞 10 · 访问量 5262

猜你喜欢

转载自blog.csdn.net/wufeng_no1/article/details/87285788