如果你发布你的blog。那么其他人就可以随便修改和添加博客了。
Rails提供了一个非常简单的http认证系统,可以非常有帮助的解决这种情况。
在PostsController里面我们需要一个方法阻止那些没有授权的用户的操作。
这时候我们可以使用http_basic_authenticate_with 方法。
这个方法通过的情况下才能处理http请求。
我们的例子里面需要除了index,show之外的方法都需要认证。
class PostsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
# GET /posts
# GET /posts.json
def index
@posts = Post.all
respond_to do |format|
# snipped for brevity我们也需要删除评论的时候需要权限。
class CommentsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
def create
@post = Post.find(params[:post_id])
# snipped for brevity现在我们如果创建一个新的post。将会显示下面的页面。

本文介绍如何在Rails应用中实现HTTP基本认证,通过设置PostsController和CommentsController中的http_basic_authenticate_with方法来保护资源,确保只有经过认证的用户才能进行创建、编辑和删除等敏感操作。
363

被折叠的 条评论
为什么被折叠?



