Is it possible to specify proxy credentials in your web.config? - c#

I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:
<defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" />
</defaultProxy>
I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.
Is there any way to do this? MSDN isn't helping me much..

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.
Create an assembly called SomeAssembly.dll with this class :
namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential("user", "password"); }
//or get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
}
Add this to your config file :
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>
This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.
This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

While I haven't found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="proxyAddress" usesystemdefault="True"/>
</defaultProxy>
</system.net>
The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server.
If your process is running under LocalService, or NetworkService, then this probably won't work. Chances are, you'll want a domain account.

You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:
1 In Web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" />
</defaultProxy>
</system.net>
In Control Panel\All Control Panel Items\Credential Manager >> Add a Generic Credential
Internet or network address: your proxy address
User name: your user name
Password: you pass
This configuration worked for me, without change the code.

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

Though its very late but it might be helpful for someone looking for solution to the same problem. I came across this question after having same problem. I am giving my solution to the problem, how I made it work.
I created the proxy using using credentials like this,
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
//get { return new NetworkCredential("user", "password"); }
get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
And then you have to register the HttpClient in the DI container like this and it will work perfectly.
services.AddHttpClient("Lynx", client =>
{
client.BaseAddress = new Uri(Configuration.GetSection("LynxUrl").Value);
}).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy()});

Related

WCF service call from class project with proxy

I need to make a WCF service call to an external 3rd party using 2-way SSL from a class project. I have added the WSDL provided by the 3rd party to my project as a Service Reference. The problem is that all calls outside our domain (*.abc.com) pass through a proxy server
http://ironport:8080
This is what I have done in my code -
var binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.Transport;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
binding.BypassProxyOnLocal = false;
binding.UseDefaultWebProxy = true;
binding.AllowCookies = false;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
var endpoint = new EndpointAddress("https://blablabla.com/GetData.svc");
var client = new AccountClient(binding, endpoint);
X509Certificate2 certi = new X509Certificate2(#"path to pfx file", "password");
client.ClientCredentials.ClientCertificate.Certificate = certi;
I make the service call using -
var account = client.ExportAccounts(obj1, obj2, obj3);
It then gives me an error -
The remote server returned an Error (407): Proxy authentication required
That is but obvious because nowhere did I mention the proxy details the request needs to go through. What I need is a way to add the following info from a web.config file of a different project into my request above -
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy proxyaddress="http://ironport:8080" />
<bypasslist>
<add address="[\w]+\.abc\.com$" />
</bypasslist>
</defaultProxy>
</system.net>
Is there some way to achieve this in code? Or do I need to go about this in a different way altogether? Let me know if I need to post more information.
You could try using the WebProxy Class. Not tested, but something like this:
WebProxy proxy = new WebProxy("http://ironport:8080");
proxy.BypassList = new string[] { "[\w]+\.abc\.com$" };
Another alternative would be to move the relevant section of the config to the web/app.config of the application that is using your class library.
ADDED
Not 100% sure this will work, but you could try adding this line to your code:
WebRequest.DefaultProxy = proxy;
Taken from this answer
Another option might be to use the ProxyAddress property of WsHttpBinding (make sure in that case you set the UseDefaultProxy to false), but I don't see a way to add a bypass list with this one.

Unable to send email in asp.net C#

I understand this topic has been well elaborated previously, but I have looked around the Internet for various solutions and nothing has helped so far.
I'm making a web application which at one point is supposed to send an email to the email that the user provided. I'm trying to send it from my gmail account.
I tried the following:
public void test()
{
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("mygmail#gmail.com", "password*"),
EnableSsl = true
};
client.Send("mygmail#gmail.com", "mygmail#gmail.com", "test", "testbody");
Console.WriteLine("Sent");
Console.ReadLine();
}
And I'm getting the following error: The server response was: 5.5.1 Authentication Required.
In my web.config file I wrote
<system.net>
<mailSettings>
<smtp>
<network host="smtp.google.com" password="" userName=""/>
</smtp>
</mailSettings>
</system.net>
But that didn't work. I also tried adding the password* and the username (mygmail#gmail.com) in the web.config instead of the empty strings for userName and password, but I still got the same error.
Could anyone please help me out?
Thank you.
Try setting UseDefaultCredentials to false before specifying your custom credentials.
See c# SmtpClient class not able to send email using gmail

WebClient DownloadStringAsync is loading very slowly

Update: I have tried HttpWebRequest and it is also exhibiting the same behaviour.
I'm trying to use WebClient DownloadStringAsync to retrieve some (very small) data in an Outlook add-in (VSTO/.Net 4.0). It's taking about 10-15 seconds before it even makes the request.
Having utilized the powers of google, I was pointed towards the fact that it was trying to pick up the proxy settings, and that I should set these to null. I tried that both in code:
WebClient serviceRequest = new WebClient();
serviceRequest.Proxy = null;
and by adding an App.config file and putting:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.net>
<defaultProxy enabled="false">
<proxy/>
<bypasslist/>
<module/>
</defaultProxy>
</system.net>
</configuration>
I added the file through the 'New Item' interface (I'm not sure if its being picked up and utilised).
Neither of these solutions has worked. Is there any things that I could try changing.
The code in question is as follows:
class MyClient
{
string url = "http://192.168.1.99:4567/contact.json?token={0}&email={1}";
WebClient serviceRequest = new WebClient();
public void getContact(string email, DownloadStringCompletedEventHandler methodName)
{
Uri target = new Uri(String.Format(url, "1234", email));
serviceRequest.Proxy = null;
if(serviceRequest.IsBusy)
{
serviceRequest.CancelAsync(); // Changed our mind and switched email
}
serviceRequest.DownloadStringCompleted += methodName;
serviceRequest.DownloadStringAsync(target);
}
}
Discovered what the problem was.
I was working on a Windows 2003 Server Virtual Machine (what I had available). As soon as I installed Windows 7 (and environment) on another VM and tried it the problem vanished.
The server machine does not have IE Enhanced Security turned on.

Poxy Proxy Problem! c#

Hi
The code below works fine to instruct the system not to use a proxy and to not auto detect one, which causes a delay without the code. However while on a network with a proxy I just get the underlying connection is closed!
So four questions:
Am I specifying the proxy correctly?
If so how do I tell it to use default proxy credentials?
Should the used want to specify credentials how are they set?
How do I set it back to the original state?
if (!Properties.Settings.Default.UseProxyServer){
//set the system not to use a proxy server
//saves the delay seen when browser set to auto detect proxy and not proxy
//is used. This works well!!
WebRequest.DefaultWebProxy = new WebProxy();
}
else{
WebRequest.DefaultWebProxy =
new WebProxy(proxyServerAddress, proxyServerPort);
//proxyServerPort is an int.
//How do I add default credentials??
}
WebClient client = new WebClient();
//specify an encoding for uploading.
client.Encoding = System.Text.Encoding.ASCII;
// Upload the data.
var myReply = client.UploadValues(addressURL, data);
I need to this in code not in the app.config.
Thanks
You can create a Web proxy object
var proxy = new WebProxy("http://server:8080");
proxy.credentials = new system.net.Credentials.DefaultCredenialCache;
proxy.Other properties
You can also create a config
<configuration>
<system.net>
<defaultProxy>
<proxy
usesystemdefaults="true"
proxyaddress="http://192.168.1.10:3128"
bypassonlocal="true"
/>
<bypasslist
<add address="[a-z]+\.contoso\.com" />
</bypasslist>
</defaultProxy>
</system.net>
</configuration>
Try this:
http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx
You may also want to check this out:
http://geekswithblogs.net/ranganh/archive/2005/08/29/51474.aspx

Proxy Authentication Required Error coming while using Google API for translation

Am using Google API for translation on passing my request to change the text language its showing the error of "Failed to get the response(407) Proxy Authendication required".
string Text = textBox1.Text;
Text = Translator.Translate(Text, Language.English, Language.French,Google.API.Translate.TranslateFormat.text);
textBox1.Text = Text;
this is sample code i tried with GoogleTranslationApi.dll please provide me some input to rectify this error.
Thanks in Advance
You need to setup you proxy server setting in the app.config.
Here is what I use with ISA proxy server (looks you are also on that).
<system.net>
<defaultProxy useDefaultCredentials="true">
<proxy autoDetect="False" usesystemdefault="True"/>
</defaultProxy>
</system.net>

Categories

Resources