在Ruby on Rails中,authenticate_with_http_basic有什么作用?

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

它有什么作用? 它似乎能够使用来自HTTP请求的login_namepassword ,然后可以将它们与users表中的login_nameencrypted_password进行比较……但是就是这样,为什么不存在单行描述?

此方法允许您实现基本的http身份validation(弹出一个小对话框询问用户名和密码的类型)。 这通常是限制对开发站点或管理区域的访问的好方法。 例如:

 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 

此函数将请求基本的http身份validation用户名和密码,或者在输入之后,它将实际检查身份validation是否正确。 换句话说,此函数将调用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'])。 您可以在此处查看有关授权function的更多信息。

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

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

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

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

HTH(谈论Rails 5要清楚)