Ruby HTTP发送API密钥Basic_auth

时间:2015-11-18 01:36:27

标签: ruby header authorization

我一直在关注GitHub Pages和 我试图将Apikey传递给webservice作为基本的auth'apiKey'=>例如'huda7da97hre3rhr1yrh0130409u1u'但是我无法弄清楚如何将它实现到方法中,或者即使它是适合它的地方。

我有一个名为connection的类,其中包含我的请求方法。我需要将'apiKey'作为标题发布而不是在正文中。我已经阅读了ruby文档,但我无法弄清楚如何将它应用于这个特定的类。

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

如果我使用Advanced Rest Client发布到服务器并将apikey放在

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

Authorization: 9c62acdda8fe12507a435345bb9b2338

并在体内

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

然后我得到

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

那么如何使用这个类发布它?。

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

1 个答案:

答案 0 :(得分:1)

基本身份验证示例:

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

或者,如果您想在请求方法中添加原始授权标头,则可以执行

 request.add_field 'Authorization', 'huda7da97hre3rhr1yrh0130409u1u'

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

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