Ruby on rails http\u基本\u验证\u是否不工作。为什么?
我刚开始学习ruby on rails,使用了以下内容: 我停在这一步上: 10安全性Ruby on rails http\u基本\u验证\u是否不工作。为什么?,ruby-on-rails,Ruby On Rails,我刚开始学习ruby on rails,使用了以下内容: 我停在这一步上: 10安全性 class PostsController < ApplicationController http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show] # GET /posts # GET /posts.json def index
class PostsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => [:index, :show]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
respond_to do |format|
[...]
class CommentsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :only => :destroy
def create
@post = Post.find(params[:post_id])
[...]
class PostsController“dhh”,:password=>“secret”,:except=>[:index,:show]
#获取/发布
#GET/posts.json
def索引
@posts=Post.all
回应待办事项|格式|
[...]
类CommentsController“dhh”、:password=>“secret”、:only=>:destroy
def创建
@post=post.find(参数[:post\u id])
[...]
但它不起作用。我的意思是,没有提示输入密码和登录,也没有错误。我就这么做了,什么都没变
有人能帮我解决这个问题吗,或者至少能给我指出解决问题的正确方向吗?这取决于您使用的Rails版本。如果是3.2,它应该可以正常工作,正如你在页面顶部看到的,它说: 本指南基于Rails 3.2。此处显示的一些代码在早期版本的Rails中不起作用。 因此,您可能想先检查一下,然后如果您的版本是较早的版本,请尝试以下方法:
class ApplicationController < ActionController::Base
USER, PASSWORD = 'dhh', 'secret'
before_filter :authentication_check, :except => :index
#Any other method
private
def authentication_check
authenticate_or_request_with_http_basic do |user, password|
user == USER && password == PASSWORD
end
end
end
显然,这一行代码(如begore所述)只能在Rails 3.2或更高版本上运行(我实际上认为它也应该在3.1版本上运行)。在没有身份验证请求的情况下,您要调用什么操作?在第一个示例中,
index
和show
不会要求密码,在第二个示例中,只有destroy
会受到密码保护。我理解这一点。但我可以在没有授权要求的情况下破坏、创造和做任何可能的事情。这就是问题所在。代码不起作用,我对此很感兴趣。它不适用于Rails-4.2.*版本,因为它给出了错误“未定义的方法'http\u basic\u authenticate\u with'for”
http_basic_authenticate_with :name => "anotherName", :password => "secret", :except => [:index, :show]