在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

http://railscasts.com/episodes/82-http-basic-authentication

对于最新的rails版本,有一个ASCIIcast ,它解释了HTTP基本身份validation的步骤。

链接在这里 。

附注:注意 ,HTTP基本身份validation以明文forms传输用户名和密码,因此您不应将此方法用于需要更高安全级别的应用程序。