在rails中进行Http基本身份validation
嗨,我来自Grails背景,是Rails的新手。 我希望在rails中进行http基本身份validation。
我有grails中的代码,它执行基本身份validation,如下所示:
def authString = "${key}:".getBytes().encodeBase64().toString() def conn = "http://something.net".toURL().openConnection() conn.setRequestProperty("Authorization", "Basic ${authString}")
是否可以使用rails完成相同的操作?
提前致谢。
使用http基本身份validation在要控制的控制器中写下面的代码
http_basic_authenticate_with :name => "user", :password => "password"
在Ruby on Rails 4中,您可以根据上下文轻松地应用站点范围或每个控制器的基本HTTP身份validation。
例如,如果您需要站点范围的身份validation:
class ApplicationController < ActionController::Base http_basic_authenticate_with name: "admin", password: "hunter2" end
或者基于每个控制器:
class CarsController < ApplicationController http_basic_authenticate_with name: "admin", password: "hunter2" end
我赞成@Nishant的答案,但想添加另一个小贴士。 您始终可以设置filter,使其仅适用于某些控制器操作,方法是only
传递或except
:
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", only: [:admin, :new, :edit, :destroy]
要么
http_basic_authenticate_with name: "admin", password: "strongpasswordhere", except: [:show]
在许多情况下非常有帮助。
# app/controllers/application_controller.rb before_filter :http_basic_auth def http_basic_auth if ENV['HTTP_AUTH'] =~ %r{(.+)\:(.+)} unless authenticate_with_http_basic { |user, password| user == $1 && password == $2 } request_http_basic_authentication end end end
然后你只需要用user:password导出你的环境变量,例如:
export HTTP_AUTH=user:pass
如果您使用的是heroku.com:
heroku config:set HTTP_AUTH=user:pass
当连接到受基本HTTP身份validation保护的HTTP端点时,我通常使用HTTParty 。 HTTParty是较低的Ruby STD类(如net / http )的简单包装器。
HTTParty与基本身份validation的示例用法。
class Delicious include HTTParty base_uri 'https://api.del.icio.us/v1' def initialize(u, p) @auth = {username: u, password: p} end def recent options={} options.merge!({basic_auth: @auth}) self.class.get('/posts/recent', options) end end delicious = Delicious.new("", "") pp delicious.recent #=> list of recent elements
检查GitHub上的更多示例 。
这个主题有一个很棒的Rails Cast
对于最新的rails版本,有一个ASCIIcast
,它解释了HTTP基本身份validation的步骤。
链接在这里 。
附注:请注意 ,HTTP基本身份validation以明文forms传输用户名和密码,因此您不应将此方法用于需要更高安全级别的应用程序。
- 缺少`secret_token`和`secret_key_base`用于’开发’环境,在`config / secrets.yml中设置这些值
- 与一些’Bignum`属性混淆
- 将数组拆分为(element =>剩余元素)对的方法
- 首先在Ruby中按哈希值对其哈希值进行排序
- Ember Engines通过ember-cli-rails在Rails引擎内部
- 使用WSL时如何从Windows访问Linux二进制文件?
- 命令行错误消息的“POSIX定义格式”是什么? 哪个标准?
- 切换到mysql数据库时rake db:load命令中的问题
- Ruby和“你必须使用OpenSSL支持重新编译Ruby或更改Gemfile中的源代码”