WEBrick proxy authentication example

I’ve never been able to find an example of using WEBrick’s HTTP proxy with authentication online before, so here’s one I figured out today, after the fold.


#!/usr/bin/env ruby
require 'webrick/httpproxy'
require 'webrick/httpauth/digestauth'
require 'webrick/httpauth/userdb'

# First work around WEBrick's braindead interrupt handling
trap("INT") { @server.shutdown }

# Noddy realm for testing
Realm = "myrealm"

# Give ourselves a user database.  The only important
# thing about our class other than the UserDB mixin
# is that it support the [] and []= method, so that storing
# and retrieving passwords can be done with self[user]
# and self[user]=password by the UserDB::get_passwd and
# UserDB::set_passwd methods.
class UserDB < Hash
  include WEBrick::HTTPAuth::UserDB
end
userdb = UserDB.new

# This can also be WEBrick::HTTPAuth::BasicAuth
userdb.auth_type = WEBrick::HTTPAuth::DigestAuth

# Give ourselves a user named "foo" with a password
# of "bar"
userdb.set_passwd(Realm, "foo", "bar")

# Set up the auth handler which the server will talk
# to.  It smells a little that the userdb needs to
# be told what class this is, instead of having it
# passed as a parameter, but it seems to work
digestauth = WEBrick::HTTPAuth::DigestAuth.new(
  :Algorithm => "MD5-sess",
  :UserDB => userdb,
  :Realm => Realm
)

# Set up the proxy itself
@server = WEBrick::HTTPProxyServer.new(
  :LogFile => $stdout,
  :BindAddress => "0.0.0.0",
  :P ort => '8080',
  :P roxyVia => false,

  # Here's where we hook up the digestauth itself, as
  # a proc that gets called for every request.
  :P roxyAuthProc => Proc.new do |req,res|
    digestauth.authenticate(req,res)
  end)
@server.start

Leave a Reply

Entries (RSS)