Robert Strauch
Robert Strauch

Reputation: 12906

HTTP Basic Authentication as default in Ruby HTTP

Using Ruby 2.2.3 I'm looking for a way to use HTTP Basic Authentication for every request. I know it is possible to define basic_auth per request:

http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth("username", "password")
response = http.request(request)

How can I "globally" use basic_auth?

Upvotes: 1

Views: 3078

Answers (1)

myconode
myconode

Reputation: 2627

basic_auth is an instance method of an Net::HTTP object. For convenience you could define a class with the desired basic_auth settings baked-in or given as arguments.

Simple example:

require 'uri'
require 'net/http'

class SimpleHTTP

  def initialize uri, user = "default_user", pass = "default_pass"
    @uri = URI.parse(uri)
    @username = user
    @password = pass
  end

  def request path=nil
    @uri.path = path if path # use path if provided
    http = Net::HTTP.new(@uri.host, @uri.port)
    req = Net::HTTP::Get.new(@uri.request_uri)
    req.basic_auth(@username, @password)
    http.request(req)
  end


end

# Simple Example
http = SimpleHTTP.new('http://www.yoursite.com/defaultpath')
http.request

# Override default user/pass
http2 = SimpleHTTP.new('http://www.yoursite.com/defaultpath', "myusername", "mypass")
http2.request

# Provide path in request method
http = SimpleHTTP.new('http://www.yoursite.com/')
http.request('/some_path')

Upvotes: 3

Related Questions