Path: blob/trunk/rb/lib/selenium/webdriver/common/driver_extensions/has_authentication.rb
1990 views
# frozen_string_literal: true12# Licensed to the Software Freedom Conservancy (SFC) under one3# or more contributor license agreements. See the NOTICE file4# distributed with this work for additional information5# regarding copyright ownership. The SFC licenses this file6# to you under the Apache License, Version 2.0 (the7# "License"); you may not use this file except in compliance8# with the License. You may obtain a copy of the License at9#10# http://www.apache.org/licenses/LICENSE-2.011#12# Unless required by applicable law or agreed to in writing,13# software distributed under the License is distributed on an14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY15# KIND, either express or implied. See the License for the16# specific language governing permissions and limitations17# under the License.1819module Selenium20module WebDriver21module DriverExtensions22module HasAuthentication23#24# Registers basic authentication handler which is automatically25# used whenever browser gets an authentication required response.26# This currently relies on DevTools so is only supported in27# Chromium browsers.28#29# @example Authenticate any request30# driver.register(username: 'admin', password: '123456')31#32# @example Authenticate based on URL33# driver.register(username: 'admin1', password: '123456', uri: /mysite1\.com/)34# driver.register(username: 'admin2', password: '123456', uri: /mysite2\.com/)35#36# @param [String] username37# @param [String] password38# @param [Regexp] uri to associate the credentials with39#4041def register(username:, password:, uri: //)42auth_handlers << {username: username, password: password, uri: uri}4344devtools.network.set_cache_disabled(cache_disabled: true)45devtools.fetch.on(:auth_required) do |params|46authenticate(params['requestId'], params.dig('request', 'url'))47end48devtools.fetch.on(:request_paused) do |params|49devtools.fetch.continue_request(request_id: params['requestId'])50end51devtools.fetch.enable(handle_auth_requests: true)52end5354private5556def auth_handlers57@auth_handlers ||= []58end5960def authenticate(request_id, url)61credentials = auth_handlers.find do |handler|62url.match?(handler[:uri])63end6465if credentials66devtools.fetch.continue_with_auth(67request_id: request_id,68auth_challenge_response: {69response: 'ProvideCredentials',70username: credentials[:username],71password: credentials[:password]72}73)74else75devtools.fetch.continue_with_auth(76request_id: request_id,77auth_challenge_response: {78response: 'CancelAuth'79}80)81end82end83end # HasAuthentication84end # DriverExtensions85end # WebDriver86end # Selenium878889