diff --git a/README.md b/README.md index 1c369a50..1f6537c9 100644 --- a/README.md +++ b/README.md @@ -105,6 +105,7 @@ and the following optional features: * `page.scroll_to` * cookie handling * drag-and-drop +* basic http authentication There are some additional features: @@ -234,6 +235,17 @@ page.within_window fb_popup do end ``` +### Basic HTTP authentication ### + +This method can be used for basic authentication: + +``` ruby +page.driver.basic_authorize('username', 'password') +``` + +It actually appends `Authorize` header to bunch of your headers, so since you've +set it don't try to use `headers=` which will overwrite it. + ## Customization ## diff --git a/lib/capybara/poltergeist/driver.rb b/lib/capybara/poltergeist/driver.rb index b76bcd61..21b999de 100644 --- a/lib/capybara/poltergeist/driver.rb +++ b/lib/capybara/poltergeist/driver.rb @@ -225,6 +225,13 @@ def cookies_enabled=(flag) browser.cookies_enabled = flag end + # Since PhantomJS doesn't send `Authorize` header with POST + # request at all, it's better to set header manually. + def basic_authorize(user, password) + credentials = ["#{user}:#{password}"].pack('m*') + add_header('Authorization', "Basic #{credentials}") + end + def debug if @options[:inspector] inspector.open diff --git a/spec/integration/driver_spec.rb b/spec/integration/driver_spec.rb index a83df687..e9a3bb03 100644 --- a/spec/integration/driver_spec.rb +++ b/spec/integration/driver_spec.rb @@ -620,5 +620,23 @@ def create_screenshot(file, *args) expect(@driver.browser.window_handles).to eq(["popup"]) expect(@driver.window_handles).to eq(["popup"]) end + + context 'basic http authentication' do + it 'does not set header' do + @session.visit '/poltergeist/basic_auth' + + expect(@session.status_code).to eq(401) + expect(@session).not_to have_content('Welcome, authenticated client') + end + + it 'sets header' do + @driver.basic_authorize('login', 'pass') + + @session.visit '/poltergeist/basic_auth' + + expect(@session.status_code).to eq(200) + expect(@session).to have_content('Welcome, authenticated client') + end + end end end diff --git a/spec/support/test_app.rb b/spec/support/test_app.rb index 7f53a847..8b265b79 100644 --- a/spec/support/test_app.rb +++ b/spec/support/test_app.rb @@ -41,6 +41,16 @@ class TestApp "slow page" end + get '/poltergeist/basic_auth' do + auth = Rack::Auth::Basic::Request.new(request.env) + if auth.provided? and auth.basic? and auth.credentials and auth.credentials == ['login', 'pass'] + 'Welcome, authenticated client' + else + headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"' + halt 401, "Not authorized\n" + end + end + get '/poltergeist/:view' do |view| render_view view end