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

35

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

我需要通过GitHub的RESTful API创建一个私有仓库。

5个回答

45

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

RestClient.get "http://username:password@example.com"

我正在寻找如何在不初始化RestClient :: Request的情况下执行身份验证。对于使用RestClient.get方法的使用+1。但是用户名和密码需要转义吗?看起来并不像看起来那么容易。 - AgostinoX
2
如果我的用户名中有'@'字符怎么办? - Sai
...但是如果你的密码中有像#这样的特殊字符,你将会得到一个异常: InvalidURIError: bad URI(is not URI?) - territorial
1
基本认证应该放在头部,除非你绝对没有其他选择。 - house9

36

这是一个可选的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没有被实例化,它可以在没有basicauth的情况下正常工作。


18
源代码来看,您可以将用户和密码作为请求对象的一部分进行指定。
您是否尝试过以下方法:
r = Request.new({:user => "username", :password => "password"})

另外,如果您在ReadMe的Shell部分向下查看,它有一个将其指定为restshell一部分的示例。

$ restclient https://example.com user pass
>> delete '/private/resource'

考虑在使用中包含该模块以改进此功能。例如,RestClient::Request 并添加更多上下文以使您提供的示例完全可用。 - Michael Wasser

8
这个功能有效,并遵循RFC 7617的Http基本身份验证

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


2
感谢Kelsey Hannan的贡献:
RestClient.get("https://example.com", 
  {
    Authorization: "Basic #{Base64::encode64('guest:guest')}"
  }
)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接