繁体   English   中英

在 Rails 中进行 Http 基本身份验证

[英]Doing a Http basic authentication in rails

嗨,我来自 Grails 背景,是 Rails 的新手。 我希望在 Rails 中进行 http 基本身份验证。

我在 grails 中有一个代码,它执行如下基本身份验证:

def authString = "${key}:".getBytes().encodeBase64().toString()
def conn = "http://something.net".toURL().openConnection()
conn.setRequestProperty("Authorization", "Basic ${authString}")

可以用rails做同样的事情吗?

在要使用 http 基本身份验证限制的控制器中编写以下代码

class ApplicationController < ActionController::Base
  http_basic_authenticate_with :name => "user", :password => "password" 
end

使用 open-uri 发出请求将如下所示:

require 'open-uri'

open("http://www.your-website.net/", 
  http_basic_authentication: ["user", "password"])

在 Ruby on Rails 4 中,您可以根据上下文轻松地在站点范围内或每个控制器上应用基本的 HTTP 身份验证。

例如,如果您需要站点范围的身份验证:

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 的回答,但想添加另一个花絮。 您始终可以设置过滤器,使其仅适用于某些控制器操作,方法是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

关于这个主题有一个很棒的 Rails Cast

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

当连接到受基本 HTTP 身份验证保护的 HTTP 端点时,我通常使用HTTParty HTTParty是低级 Ruby STD 类(如net/http )的简单包装器。

HTTParty与基本身份验证的示例用法。

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("<username>", "<password>")

pp delicious.recent #=> list of recent elements

在 GitHub 上查看更多示例

以上答案是正确的,但最好不要在源代码中输入用户和密码。

最好在环境变量中有密码用于生产(代码中可以用于开发)

class YourController..
  http_basic_authenticate_with name: ENV["HTTP_BASIC_AUTH_USER"], password: ENV["HTTP_BASIC_AUTH_PASSWORD"], if: -> { ENV['RAILS_ENV'] == 'production' }
  http_basic_authenticate_with name: "user", password: "pass", if: -> { ENV['RAILS_ENV'] != 'production' }

对于最新的 rails 版本,有一个ASCIIcast解释了HTTP Basic Authentication 的步骤。

链接在 这里

旁注:注意,HTTP 基本身份验证以明文形式传输用户名和密码,因此对于需要更高级别安全性的应用程序,不应使用此方法。

您可以使用request.basic_auth传递身份验证所需的基本身份验证参数。 content_type可以根据需要更改。

您必须包括 -

require 'net/http'
require 'uri'

请求代码将如下所示 -

  key = "awknfkjn93013nksdkjnsd09920930jwkslkd102"
  token = "qs90si90w4jm309w0kd5009kdw700i29012dfmk"
  uri = URI("http://something.net")
  request = Net::HTTP::Post.new(uri)
  request.content_type = 'application/x-www-form-urlencoded'
  request.basic_auth(key, token)
  payload = {
              your_payload_key=> "your_payload_value"
            }
  request.set_form_data(payload)
  request_options = {
      use_ssl: uri.scheme == "https"
  }
  response = Net::HTTP.start(uri.hostname, uri.port, request_options) do |http|
    http.request(request)
  end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM