有谁知道如何使用RestClient进行基本身份验证?
我需要通过他们的 RESTful API 在 GitHub 上创建一个私有存储库。
最简单的方法是在 URL 中嵌入详细信息:
RestClient.get "http://username:password@example.com"
这是一个工作代码示例,其中我支持可选的 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
没有实例化,没有基本身份验证它可以正常工作。
从源代码看来,您可以将用户和密码指定为请求对象的一部分。
您是否尝试过类似的方法:
r = Request.new({:user => "username", :password => "password"})
此外,如果您查看自述文件的 Shell 部分,它有一个将其指定为 restshell
.
$ restclient https://example.com user pass
>> delete '/private/resource'
这适用并遵循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
感谢凯尔西汉南:
RestClient.get("https://example.com",
{
Authorization: "Basic #{Base64::encode64('guest:guest')}"
}
)
RestClient.post("https://example.com",
{ }.to_json,
{
Authorization: "Basic #{Base64::encode64('guest:guest')}"
}
)