How do you configure your browser to use a proxy with Selenium? The code looks something like this:
Since we’re Selenium users, we’ll be using a proxy that allows us to programmatically start and stop it, and hook into the request/response chain via our code, and modify the results in order to interpret and replace the headers as needed. Any number of proxies could be used in this project. Many Selenium users have had great success using BrowserMob Proxy, or there are commercial options like Fiddler. Since I personally prefer FOSS options, and don’t want to leave the .NET ecosystem, for our examples here, we’ll be using BenderProxy. Here’s the code for setting that up.
Now, how do we wire up the proper processing to mimic the browser’s processing of an authentication prompt? We need to implement the addition of an Authorization header that provides the correct value, for the authentication scheme requested by the server. BenderProxy’s OnResponseReceived handler happens after the response has been received from the web server, but before it’s forwarded along to the browser for rendering. That gives us the opportunity to examine it, and resend another request with the proper credentials in the proper format. We’re using the Basic authentication scheme in this example, and once again using The Internet sample application. Here’s the code for the method:
Running the code, we’ll see that when the Selenium code is run, the browser will show the authorized page, as we intended. As you can tell from the implementation code, Basic authentication is pretty simple, sending the Base64 encoding of “userName:passsword”. Its simplicity is also one reason it’s not used very often, as it sends the credentials across the wire, essentially in clear text. There are other, more secure authentication schemes available, and they can be automated in similar ways. The trick is knowing how to specify the value for the Authentication header. In the next post in the series, we’ll look at another authentication mechanism, and how to handle something a little more complicated.