class HTTPAuth::Basic

Basic

The Basic class provides a number of methods to handle HTTP Basic Authentication. In Basic Authentication the server sends a challenge and the client has to respond to that with the correct credentials. These credentials will have to be sent with every request from that point on.

On the server

On the server you will have to check the headers for the ‘Authorization’ header. When you find one unpack it and check it against your database of credentials. If the credentials are wrong you have to return a 401 status message and a challenge, otherwise proceed as normal. The code is meant as an example, not as runnable code.

def check_authentication(request, response)
  credentials = HTTPAuth::Basic.unpack_authorization(request['Authorization'])
  if ['admin', 'secret'] == credentials
    response.status = 200
    return true
  else
    response.status = 401
    response['WWW-Authenticate'] = HTTPAuth::Basic.pack_challenge('Admin Pages')
    return false
  end
end

On the client

On the client you have to detect the WWW-Authenticate header sent from the server. Once you find one you should send credentials for that resource any resource ‘deeper in the URL space’. You may send the credentials for every request without a WWW-Authenticate challenge. Note that credentials are valid for a realm, a server can use multiple realms for different resources. The code is meant as an example, not as runnable code.

def get_credentials_from_user_for(realm)
  if realm == 'Admin Pages'
   return ['admin', 'secret']
  else
   return [nil, nil]
  end
end

def handle_authentication(response, request)
  unless response['WWW-Authenticate'].nil?
    realm = HTTPAuth::Basic.unpack_challenge(response['WWW-Authenticate])
    @credentials[realm] ||= get_credentials_from_user_for(realm)
    @last_realm = realm
  end
  unless @last_realm.nil?
    request['Authorization'] = HTTPAuth::Basic.pack_authorization(*@credentials[@last_realm])
  end
end