C# Selenium Firefox Set socks proxy with Auth - c#

In C# I'm trying to set socks proxy with authentification in firefox.
This doesn't work
Proxy proxy = new Proxy();
proxy.SocksProxy = sProxyIP + ":" + sProxyPort;
proxy.SocksUserName = sProxyUser;
proxy.SocksPassword = sProxyPass;
options.Proxy = proxy;
_driver = new FirefoxDriver(service, options);
This doesn't work too
profile.SetPreference("network.proxy.socks", sProxyUser + ":" + sProxyPass + "#" + sProxyIP + ":" + sProxyPort);
profile.SetPreference("network.proxy.socks_port", sProxyPort);
How can I solve this?

As far as I know you can't do it in that way with Firefox. You need to add a new Firefox profile and then to work with it with Selenium. On this profile you need to save the proxy information and to save the username and password.
You can set a Firefox profile following this steps link. Then it is easy to do the job. I use that code:
FirefoxProfile profile = new FirefoxProfile(pathToProfile);
FirefoxOptions options = new FirefoxOptions();
options.Profile = profile;
driver = new FirefoxDriver(options);
Then you would have to suppress the alert for username and password verification. You can use two ways of doing that. The first one is to do it programmatically. Something like that:
var alert = driver.SwitchTo().Alert();
alert.Accept();
The other way is to do that from Firefox Profile Settings.

After a lot of researching, here is the solution I decided to go with.
It's a dirty hack, but it works.
I used AutoitX in order to automate the proxy auth window but had to use System.Windows.Automation in order to get the right auth window since my app will be multithreaded.
sProxyIP = "154.5.5.5";
sProxyUser = "user here";
sProxyPass = "pass here";
sProxyPort = 4444;
//Set proxy
profile.SetPreference("network.proxy.socks", sProxyIP);
profile.SetPreference("network.proxy.socks_port", sProxyPort);
//deal with proxy auth
_driver.Manage().Timeouts().PageLoad = TimeSpan.FromMilliseconds(0);
WebsiteOpen(#"https://somewebsite.com/");
AuthInProxyWindow(sProxyUser, sProxyPass);
_driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(60);
void ProxyAuthWindow(string login, string pass)
{
try
{
//wait for the auth window
var sHwnd = AutoItX.WinWait("Authentication Required", "", 2);
AutoItX.WinSetOnTop("Authentication Required", "", 1);
//we are using Windows UIA so we make sure we got the right auth
//dialog(since there will be multiple threads we can easily hit the wrong one)
var proxyWindow = AutomationElement.RootElement.FindFirst(TreeScope.Subtree,
new PropertyCondition(AutomationElement.ClassNameProperty, "MozillaDialogClass"));
string hwnd = "[handle:" + proxyWindow.Current.NativeWindowHandle.ToString("X") + "]";
AutoItX.ControlSend(hwnd, "", "", login, 1);
AutoItX.ControlSend(hwnd, "", "", "{TAB}", 0);
AutoItX.ControlSend(hwnd, "", "", pass, 1);
AutoItX.ControlSend(hwnd, "", "", "{ENTER}", 0);
}
catch
{
}
}

Related

Not able to login to DocuSign API from MVC application

I am trying to connect with DocuSign using DocuSign API in my C# MVC application:
// initialize client for desired environment (for production change to www)
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");
Configuration.Default.ApiClient = apiClient;
// configure 'X-DocuSign-Authentication' header
string authHeader = "{\"Username\":\"" + credentials.Username + "\", \"Password\":\"" + credentials.Password + "\", \"IntegratorKey\":\"" + credentials.IntegratorKey + "\"}";
if (!Configuration.Default.DefaultHeader.ContainsKey("X-DocuSign-Authentication"))
{
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
}
// login call is available in the authentication api
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
On authApi.Login() I am getting below error:
Error calling Login: Message.TemplateName: authenticationrequired
Message.Language: Fallback
McAfee Web Gateway - Notification - Authentication Required
I think this error might be due to my proxy in my company system.
Can anyone please let me know if they are familiar with this error.
Thanks advance for the response!!
I finally figured out the resolution,
As network team was not ready to include URL in their white list.(not sure why??)
public DocuSignClient(Credentials credentials)
{
// initialize client for desired environment (for production change to www)
ApiClient apiClient = new ApiClient("https://demo.docusign.net/restapi");
Configuration.Default.ApiClient = apiClient;
// configure 'X-DocuSign-Authentication' header
string authHeader = "{\"Username\":\"" + credentials.Username + "\", \"Password\":\"" + credentials.Password + "\", \"IntegratorKey\":\"" + credentials.IntegratorKey + "\"}";
if (!Configuration.Default.DefaultHeader.ContainsKey("X-DocuSign-Authentication"))
{
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
}
WebProxy webProxy = new WebProxy("http://proxy.corp.ups.com:8080", true)
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential("ABC", "XYZ")
};
apiClient.RestClient.Proxy = webProxy;
// login call is available in the authentication api
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// parse the first account ID that is returned (user might belong to multiple accounts)
this.AccountId = loginInfo.LoginAccounts[0].AccountId;
}
Please make sure to follow the sequence for WebProxy.

Windows Impersonation Issue

Hi guys i'm having a hard time to figure out why the Impersonation in WindowsIdentity does not work.
I will present the idea and also the code in the following.
So the idea is that i need to access within my application another application API.
public async Task<UserHrtbProfileDTO> HasHrtbAccessAsync(int userId, string systemUser)
{
WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
using (identity.Impersonate())
{
using (HttpClientHandler handler = new HttpClientHandler
{
Credentials = CredentialCache.DefaultNetworkCredentials,
UseDefaultCredentials = true
})
{
using (HttpClient client = new HttpClient(handler, true))
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string requestURI = string.Format(ConfigurationManager.AppSettings["HRTB:Profile_Url"], userId);
HttpResponseMessage response = await client.GetAsync(requestURI);
return response.RequestMessage.RequestUri.OriginalString.Contains(requestURI)
? new UserHrtbProfileDTO
{
HrtbProfileUrl = string.Format(ConfigurationManager.AppSettings["HRTB:Profile_Url"], userId),
ResponseURI = response.RequestMessage.RequestUri.AbsoluteUri,
}
: new UserHrtbProfileDTO
{
ResponseURI = response.RequestMessage.RequestUri.AbsoluteUri,
RequestURI = requestURI,
HasHrtbAccess = false,
IdentityUserName = identity.Name + "\n" + identity.IsAuthenticated + "\n" + identity.AuthenticationType + "\n" + identity.ImpersonationLevel + "\n"
};
}
}
}
}
If i'm running on local IIS the behavior is OK, i have access where i need to have and the access is being denied where i don't have it. The API response for which the request is made returns the response that i expect.
But when i deploy and run from a server the response is different thus the behavior is not as it should.
I'm guessing that the request is not emitted from the perspective of the user that has made it.
Any idea ,suggestions, or a different approach in which i can solve the issue.
Thank you all.
For me it worked enabling impersonation from web.config file and set the IIS application pool to classic managed pipeline.
If you have any other knowledge of other solutions, please share.
Thank you

Provide username and password for proxy - Selenium

I'm trying the below code. But its still giving dialog box for entering username and password when firefox browser starts. Where am I wrong?
FirefoxProfile profile = new FirefoxProfile();
Proxy firefox_proxy = new Proxy();
firefox_proxy.HttpProxy = proxy;
firefox_proxy.SslProxy = proxy;
profile.SetProxyPreferences(firefox_proxy);
Firefoxdriver driver = new FirefoxDriver(new FirefoxBinary(), profile, TimeSpan.FromMinutes(3));
driver.Navigate().GoToUrl("http://" + proxy_username + ":" + proxy_password + "#www.xyz.com/");
You should try with https:// instead of http:// as on some sites the Basic Authentication works on secure network only.
Syntax: driver.Navigate().GoToUrl("https://proxy_username:proxy_password#www.xyz.com/");

Setting a proxy for Chrome Driver in Selenium

I am using Selenium Webdriver using C# for Automation in Chrome browser.
I need to check if my webpage is blocked in Some regions(some IP ranges). So I have to set a proxy in my Chrome browser. I tried the below code. The proxy is being set but I get an error. Could someone help me?
ChromeOptions options = new ChromeOptions();
options.AddArguments("--proxy-server=XXX.XXX.XXX.XXX");
IWebDriver Driver = new ChromeDriver(options);
Driver.Navigate().GoToUrl("myUrlGoesHere");
When I run this code, I get the following message in my Chrome browser: I tried to enable the Proxy option, but the ' Change proxy settings' option is disabled.
Unable to connect to the proxy server
A proxy server is a server that acts as an intermediary between your computer and other servers. Your system is currently configured to use a proxy, but Google Chrome can't connect to it.
If you use a proxy server...
Check your proxy settings or contact your network administrator to ensure the proxy server is working. If you don't believe you should be using a proxy server: Go to the Chrome menu > Settings > Show advanced settings... > Change proxy settings... > LAN Settings and deselect
"Use a proxy server for your LAN".
Error code: ERR_PROXY_CONNECTION_FAILED*
I'm using the nuget packages for Selenium 2.50.1 with this:
ChromeOptions options = new ChromeOptions();
proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3330";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
var chromedriver = new ChromeDriver(options);
If your proxy requires user log in, you can set the proxy with login user/password details as below:
options.AddArguments("--proxy-server=http://user:password#yourProxyServer.com:8080");
Please Following code, this will help you to change the proxy
First create chrome extension and paste the following java script
code.
Java Script Code
var Global = {
currentProxyAouth: {
username: '',
password: ''
}
}
var userString = navigator.userAgent.split('$PC$');
if (userString.length > 1) {
var credential = userString[1];
var userInfo = credential.split(':');
if (userInfo.length > 1) {
Global.currentProxyAouth = {
username: userInfo[0],
password: userInfo[1]
}
}
}
chrome.webRequest.onAuthRequired.addListener(
function(details, callbackFn) {
console.log('onAuthRequired >>>: ', details, callbackFn);
callbackFn({
authCredentials: Global.currentProxyAouth
});
}, {
urls: ["<all_urls>"]
}, ["asyncBlocking"]);
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log('Background recieved a message: ', request);
POPUP_PARAMS = {};
if (request.command && requestHandler[request.command])
requestHandler[request.command](request);
}
);
C# Code
var cService = ChromeDriverService.CreateDefaultService();
cService.HideCommandPromptWindow = true;
var options = new ChromeOptions();
options.AddArguments("--proxy-server=" + "<< IP Address >>" + ":" + "<< Port Number >>");
options.AddExtension(#"C:\My Folder\ProxyChanger.crx");
options.Proxy = null;
string userAgent = "<< User Agent Text >>";
options.AddArgument($"--user-agent={userAgent}$PC${"<< User Name >>" + ":" + "<< Password >>"}");
IWebDriver _webDriver = new ChromeDriver(cService, options);
_webDriver.Navigate().GoToUrl("https://whatismyipaddress.com/");

C# Selenium WebDriver FireFox Profile - using proxy with Authentication

When you set proxy server parameter in the code below if your proxy server requires authentication then FireFox will bring Authentication dialog and basically you can't fill it in automatically.
So is there is anyway to set USERNAME and PASSWORD ?
FirefoxProfile profile = new FirefoxProfile();
String PROXY = "192.168.1.100:8080";
OpenQA.Selenium.Proxy proxy = new OpenQA.Selenium.Proxy();
proxy.HttpProxy=PROXY;
proxy.FtpProxy=PROXY;
proxy.SslProxy=PROXY;
profile.SetProxyPreferences(proxy);
FirefoxDriver driver = new FirefoxDriver(profile);
If you try to format proxy string to something like that http://username:pass#192.168.1.1:8080
You get error that string is invalid. So I wonder there is must be a way of achieving this.
Any help would be appreciated.
String PROXY = "http://login:pass#proxy:port";
ChromeOptions options = new ChromeOptions();
options.AddArguments("user-data-dir=path/in/your/system");
Proxy proxy = new Proxy();
proxy.HttpProxy = PROXY;
proxy.SslProxy = PROXY;
proxy.FtpProxy = PROXY;
options.Proxy = proxy;
// Initialize the Chrome Driver
using (var driver = new ChromeDriver(options))
You can write own firefox extension for proxy, and launch from selenium. You need write 2 files and pack it.
background.js
var proxy_host = "YOUR_PROXY_HOST";
var proxy_port = YOUR_PROXY_PORT;
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: proxy_host,
port: proxy_port
},
bypassList: []
}
};
function proxyRequest(request_data) {
return {
type: "http",
host: proxy_host,
port: proxy_port
};
}
browser.proxy.settings.set({value: config, scope: "regular"}, function() {;});
function callbackFn(details) {
return {
authCredentials: {
username: "YOUR_USERNAME",
password: "YOUR_PASSWORD"
}
};
}
browser.webRequest.onAuthRequired.addListener(
callbackFn,
{urls: ["<all_urls>"]},
['blocking']
);
browser.proxy.onRequest.addListener(proxyRequest, {urls: ["<all_urls>"]});
manifest.json
{
"name": "My Firefox Proxy",
"version": "1.0.0b",
"manifest_version": 2,
"permissions": [
"browsingData",
"proxy",
"storage",
"tabs",
"webRequest",
"webRequestBlocking",
"downloads",
"notifications",
"<all_urls>"
],
"background": {
"scripts": ["background.js"]
},
"browser_specific_settings": {
"gecko": {
"id": "myproxy#example.org"
}
}
}
Next you need packed this files to zip archive in DEFLATED mode with .xpi at end like my_proxy_extension.xpi.
You have two choices:
Sign your extension Here you can read more about verify extension and extension's structure
OR
Run unsigned. For this step:
Open firefox flags at about:config and set options xpinstall.signatures.required to false
OR
Update firefox profile in:
Windows: C:\Program Files\Mozilla Firefox\defaults\pref\channel-prefs.js
Linux: /etc/firefox/syspref.js
Add next line to end of file:
pref("xpinstall.signatures.required",false);
After this steps run selenium and install this extension:
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension(new File("path/to/my_proxy_extension.xpi"));
driver = new FirefoxDriver(profile);
What you can do is to create a profile and save the authentication data in it.
If your profile is called "webdriver" you can select it from your code in the initialization:
ProfilesIni allProfiles = new ProfilesIni();
FirefoxProfile profile = allProfiles.getProfile("WebDriver");
profile.setPreferences("foo.bar",23);
WebDriver driver = new FirefoxDriver(profile);
Did it with MS UI Automation without AutoIt:
public void AuthInProxyWindow (string login, string pass)
{
var proxyWindow = AutomationElement.RootElement
.FindFirst(TreeScope.Subtree,
new PropertyCondition(AutomationElement.ClassNameProperty, "MozillaDialogClass"));
var edits = proxyWindow.FindAll(TreeScope.Subtree,
new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
var unamePoint = edits[1].GetClickablePoint();
Mouse.MoveTo(new Point((int) unamePoint.X, (int) unamePoint.Y));
Mouse.Click(MouseButton.Left);
SendKeys.SendWait(login);
var pwdPoint = edits[2].GetClickablePoint();
Mouse.MoveTo(new Point((int) pwdPoint.X, (int) pwdPoint.Y));
Mouse.Click(MouseButton.Left);
SendKeys.SendWait(pass);
Keyboard.Press(Key.Return);
Logger.Debug("Authefication in Firefox completed succesfully");
}
Mouse moves by Microsoft.TestApi
To stop firefox from giving you the auth pop up simple make sure you set your proxy URL to include the auth details in the setup stage as below:
var myProxy = user + ":" + pass + "#" + proxyIP + ":" + proxyPORT;
options.SetPreference("network.proxy.type", 1);
options.SetPreference("network.proxy.http", myProxy);
options.SetPreference("network.proxy.http_port", proxyPORT);
options.SetPreference("general.useragent.override", useragent);
driver = new FirefoxDriver(driverService, options);

Categories

Resources