如何使用RestClient进行基本身份验证?

nev*_*ame 33 ruby github rest-client

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

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

ops*_*psb 42

最简单的方法是在URL中嵌入细节:

RestClient.get "http://username:password@example.com"
Run Code Online (Sandbox Code Playgroud)

  • 如果我的用户名有"@"字符怎么办? (2认同)

bgu*_*pta 31

下面是一个工作代码示例,其中我支持可选的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
Run Code Online (Sandbox Code Playgroud)

请注意,如果@my_user@mypass没有实例化时,没有基本验证工作正常.


Mik*_*bee 17

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

你尝试过类似的东西:

r = Request.new({:user => "username", :password => "password"})
Run Code Online (Sandbox Code Playgroud)

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

$ restclient https://example.com user pass
>> delete '/private/resource'
Run Code Online (Sandbox Code Playgroud)


Kel*_*nan 6

这有效并遵循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

Run Code Online (Sandbox Code Playgroud)