Ruby HTTP 发送 API 密钥 Basic_auth

Ruby HTTP sending API key Basic_auth

我一直在关注 GitHub Pages 上的教程并且 例如,我正在尝试将 Apikey 作为基本身份验证 'apiKey' => 'huda7da97hre3rhr1yrh0130409u1u' 传递给 Web 服务,但我无法弄清楚如何将它实现到方法中,或者即使那是它的正确位置.

我有一个名为 class 的连接,其中包含我的请求方法。我需要 post 'apiKey' 为 header 而不是 body。我已经阅读了 ruby 文档,但我不知道如何将它应用到这个特定的 class。

require "net/http"
require "uri"
require "ostruct"
require "json"


class Connection
    ENDPOINT = "http://localhost"
    APP_LOCATION = "/task_manager/v1/"

VERB_MAP = {
    :get    => Net::HTTP::Get,
    :post   => Net::HTTP::Post,
    :put    => Net::HTTP::Put,
    :delete => Net::HTTP::Delete
}

def initialize(endpoint = ENDPOINT)
    uri = URI.parse(endpoint)
    @http = Net::HTTP.new(uri.host, uri.port)
end

def get(path, params)
    request_json :get, path, params
end

def post(path, params)
    request_json :post, APP_LOCATION + path, params
end

def put(path, params)
    request_json :put, path, params
end

def delete(path, params)
    request_json :delete, path, params
end

private
def request_json(method, path, params)
    response = request(method, path, params)
    body = JSON.parse(response.body)

    OpenStruct.new(:code => response.code, :body => body)
rescue JSON::ParserError
    response
end

def request(method, path, params = {})
    case method     
    when :get
        full_path = encode_path_params(path, params)
        request = VERB_MAP[method.to_sym].new(full_path)
    else            
        request = VERB_MAP[method.to_sym].new(path)
        request.set_form_data(params)
    end
    @http.request(request)
end

def encode_path_params(path, params)
    encoded = URI.encode_www_form(params)
    [path, encoded].join("?")
end

end

如果我 post 使用 Advanced Rest Client 连接到服务器并将 apikey 放在

http://localhost/task_manager/v1/tasks?=

header

Authorization: 9c62acdda8fe12507a435345bb9b2338

并在 body

email=free%40mail.com&password=free&task=test

然后我得到

    {
error: false
message: "Task created successfully"
task_id: 5
}

那么我如何 post 使用这个 class 呢?

        connection = Connection.new
        result = connection.post("task", {'task' => 'task'})

基本身份验证示例:

req = Net::HTTP::Get.new(uri)
req.basic_auth 'user', 'pass'

http://docs.ruby-lang.org/en/trunk/Net/HTTP.html#class-Net::HTTP-label-Basic+Authentication

或者,如果您想在请求方法中添加原始授权 header,您可以这样做

 request.add_field 'Authorization', 'huda7da97hre3rhr1yrh0130409u1u'

但基本认证通常意味着有一个用户名和一个密码。使用您的 API 密钥 - 我不确定您是否真的需要基本身份验证。我不知道你 API 实际需要什么,但如果你还没有尝试过,你可以尝试将 api 密钥作为附加参数发送

result = connection.post("register", {'email' => email, 'name' => name, 'password' => password, 'apiKey' => 'huda7da97hre3rhr1yrh0130409u1u' })