34

有谁知道如何使用RestClient进行基本身份验证?

我需要通过他们的 RESTful API 在 GitHub 上创建一个私有存储库。

4

5 回答 5

44

最简单的方法是在 URL 中嵌入详细信息:

RestClient.get "http://username:password@example.com"
于 2010-11-19T08:32:11.423 回答
34

这是一个工作代码示例,其中我支持可选的 basicauth 但不要求将用户和密码嵌入到 URL 中:

def get_collection(path)
  response = RestClient::Request.new(
    :method => :get,
    :url => "#{@my_url}/#{path}",
    :user => @my_user,
    :password => @my_pass,
    :headers => { :accept => :json, :content_type => :json }
  ).execute
  results = JSON.parse(response.to_str)
end

请注意是否实例化@my_user并且@mypass没有实例化,没有基本身份验证它可以正常工作。

于 2011-10-08T18:50:35.373 回答
18

源代码看来,您可以将用户和密码指定为请求对象的一部分。

您是否尝试过类似的方法:

r = Request.new({:user => "username", :password => "password"})

此外,如果您查看自述文件的 Shell 部分,它有一个将其指定为 restshell.

$ restclient https://example.com user pass
>> delete '/private/resource'
于 2010-09-11T22:06:13.953 回答
7

这适用并遵循RFC 7617 for Http Basic Authentication


RestClient::Request.execute(
  method: :post,
  url: "https://example.com",
  headers: { "Authorization" => "Basic " + Base64::encode64(auth_details) },
  payload: { "foo" => "bar"}
)


def auth_details
  ENV.fetch("HTTP_AUTH_USERNAME") + ":" + ENV.fetch("HTTP_AUTH_PASSWORD")
end

于 2019-12-02T21:32:00.897 回答
2

感谢凯尔西汉南:

RestClient.get("https://example.com", 
  {
    Authorization: "Basic #{Base64::encode64('guest:guest')}"
  }
)

RestClient.post("https://example.com", 
  {  }.to_json,
  {
    Authorization: "Basic #{Base64::encode64('guest:guest')}"
  }
)
于 2020-12-11T11:01:12.437 回答