在Ruby on Rails中,authenticate_with_http_basic做了什么?

nop*_*ole 19 ruby-on-rails ruby-on-rails-3

Restful Authentication使用authenticate_with_http_basic,但在网上搜索可以找到许多没有描述的页面.在官方http://api.rubyonrails.org/上,它也可以找到,除了没有描述,没有评论,没有规范.

它有什么作用?这似乎是能够使用login_namepassword从HTTP请求,然后他们可以相比的login_name,并encrypted_passwordusers表......但就是这样,为什么不在那里甚至1行的描述?

Pan*_*kos 24

此方法允许您实现基本的http身份验证(弹出一个小对话框,要求输入用户名和密码).这通常是限制对开发站点或管理区域的访问的好方法.例如:

class AdminController < ApplicationController
  before_filter :authenticate

  def authenticate
    authenticate_or_request_with_http_basic('Administration') do |username, password|
      username == 'admin' && password == 'password'
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

此函数将请求基本的http身份验证用户名和密码,或者在输入之后,它将实际检查身份验证是否正确.换句话说,此函数将调用authenticate_with_http_basic或它将调用request_http_basic_authentication.您可以阅读更多相关信息,并在此处查看更多示例.您通常会调用authenticate_or_request_with_http_basic而不是调用authenticate_with_http_basic或request_http_basic_authentication,因为前一个函数将适用于后面的所有函数.

PS:authenticate_with_http_basic不使用POST变量,它使用头信息来获取用户名和密码(request.env ['HTTP_AUTHORIZATION']).您可以在此处查看有关授权功能的更多信息.


ako*_*nov 7

如果我能在任何地方阅读它们,一些细节可以节省我的时间.

我摆弄它.authenticate_with_http_basic只需从请求中读取basic-auth user/pass,并在请求中出现此类信息时执行内部块.如果客户端没有发送auth,则返回nil.否则它返回块评估的任何内容.

因此您可以使用返回值来决定是否执行request_http_basic_authentication,返回403禁止或呈现内容.

仅供参考,如果您从注册为before_action钩子的方法运行它,我注意到该方法的返回值被忽略.如果是方法rendered某事或者redirected,则不执行该操作.如果方法没有renderredirect,则执行操作.

HTH(谈论Rails 5要清楚)