I have been trying to embed a WebBrowser control in a custom WinForms application that points to a secured web application running in IIS for some time now and have finally found a solution that works. There are plenty of posts on the internet that pass an authorization header in to the Navigate method of the WebBrowser control but I only found one that combines that technique with adding the username and password to the URL. Without adding the second technique, the initial page loads without prompting for credentials but when you click any link on that page, it then prompts you for credentials again.
The combination of both techniques solved my problem but is not very secure. Our web application is accessed via SSL but passing the username and password in the URL is not recommended. In our case, the application is secured, but not a major risk if compromised – this is not always the case so be sure to understand your security needs before implementing this code. You only need to do it this way if using the WebBrowser control, if you were to use the WebClient or HttpWebRequest objects, you would be able to use the NetworkCredential object to pass in the credentials – which we use in other parts of the same application or when passing permissions to web service calls (which I do here: https://ericniemiec.wordpress.com/2009/02/20/programmatically-add-credentials-to-an-asmx-web-service-that-is-password-protected-in-c/ ).
In my case, the web server is running IIS 7.5, and is setup with Basic authentication (no Windows Authentication is enabled), a default domain and realm is set and a SSL certificate is loaded for this site.
Here is the code to make this all work, even though the header says ‘Basic’, this works for passing domain credentials as long as the default domain is set in the Basic Authentication dialog in IIS.
1
2
3
4
5
6
|
string userName =
"first.last"
;
string
password
=
"SuperSecretPW"
;
string hdr =
"Authorization: Basic "
+
Convert
.ToBase64String(Encoding.ASCII.GetBytes(userName +
":"
+
password
)) + System.Environment.NewLine;
webBrowser.Navigate(String.Format(
"https://{0}:{1}@www.your-securesite.com/your-application/default.aspx"
, userName,
password
),
null
,
null
, hdr);
|
Even though I had used this technique years ago, it was not until I saw this post that it hit me:
Hope this helps!
-Eric Niemiec