how change Username And Password to proxy - asp.net

I have username and password to login a web site but i need login with proxy
how can change username and pass to proxy
i can login to web site with this url www.mydomain.com?user=1&pass=2 or insert user and pass to login page
how i can login web site with HttpWebRequest in asp.net C#?
<code>
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Url);
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
</code>

It is well documented on MSDN, see HttpWebRequest.Proxy Property.
The local computer or application config file may specify that a
default proxy be used. If the Proxy property is specified, then the
proxy settings from the Proxy property override the local computer or
application config file and the HttpWebRequest instance will use the
proxy settings specified. If no proxy is specified in a config
file and the Proxy property is unspecified, the HttpWebRequest
class uses the proxy settings inherited from Internet Explorer on the
local computer. If there are no proxy settings in Internet Explorer,
the request is sent directly to the server.
There is also longer sample code, the most important part is:
WebProxy myProxy = new WebProxy();
myProxy.Address = "your proxy url";
myProxy.Credentials = new NetworkCredential("login", "password");
Request.Proxy = myProxy;

Related

With ServiceStack Auth, is there a way to make the redirects always be HTTPS?

For website logins I am using ServiceStack's Authentication feature with the Authenticate attribute, the CredentialsAuthProvider and the UserAuth repository. It is working great, however, in production we put all IIS hosts behind a loadbalancer that serves only HTTPS by design (forwarding all requests on port 443 to port 80 on the IIS instances). This creates a problem - the Authenticate attribute redirects to the login page on HTTP port 80 only (I think because it sees only the proxied request Url, not the original). This results in a failed request in the browser because the load balancer does not do HTTP and does not redirect HTTP requests to HTTPS. We cannot configure IIS to also be HTTPS only.
Is there a way to make the redirects in the Auth provider always be HTTPS? Or, can the Auth provider look at the HTTP headers for the X-Forwarded-Proto to see that the login page request should be over HTTPS?
Here is the reply from Demis Bellot on the ServiceStack Customer Forums:
Some of the OAuth urls are specified in the configuration:
https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#oauth-configuration
For other autogenerated Urls you can set it to use https:
SetConfig(new HostConfig {
UseHttpsLinks = true
});
Which should modify the BaseUrl used in the latest v4.0.33 release.
You can also override AppHost. ResolveAbsoluteUrl method to
introspect/customize urls.
And my implementation of the AppHost.ResolveAbsoluteUrl override
public override string ResolveAbsoluteUrl(string virtualPath, IRequest httpReq)
{
virtualPath = virtualPath.SanitizedVirtualPath();
var absoluteUrl = httpReq.GetAbsoluteUrl(virtualPath);
return httpReq.Headers["X-Forwarded-Proto"] != null
&& httpReq.Headers["X-Forwarded-Proto"].Equals("https", StringComparison.InvariantCultureIgnoreCase)
? absoluteUrl.Replace("http://", "https://") : absoluteUrl;
}
(The loadbalancer and instances are at AWS by the way)

Can't see WebClient post request in Fiddler

I have an ASP.NET WebForms app (sender) which sends a WebClient post request to another ASP.NET app (receiver) on the same dev machine. The WebClient post is initiated by clicking a button in the sender app. It's a test app and the form has only the button. I can see the post from the button in Fiddler but I don't see the post request from the WebClient method. Why?
I know the WebClient post runs successfully because the breakpoint is hit in the receiver app and the Forms collection has the value of the input field from the WebClient request from the sender app. (Using Windows 8.1)
Update This is the call:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "FirstName=John";
var result = client.UploadString("http://localhost/testform/default.aspx", "POST", data);
Console.WriteLine(result);
}
.NET and IE(before version 9) are not sending requests to localhost through any proxies. There are 3 possible solutions:
Use machine name or hostname: http://<machine name>/testform/default.aspx
Add ipv4.fiddler to the URL: http://localhost.fiddler/testform/default.aspx
Add custom rule to the fiddler:
static function OnBeforeRequest(oSession:Fiddler.Session){
if (oSession.HostnameIs("MYAPP")) {
oSession.host = "<put your ip address and port here>";
}
}
Then you should be able to capture traffic through http://myapp/testform/default.aspx
Reference Problem: Traffic sent to http://localhost or http://127.0.0.1 is not captured.
Could be multiple things. Here are some possibilities
You have Fiddler set to filter to only show things from a particular process (or some other type of filter but process is the easiest one to accidentally turn on)
You have not turned on HTTPS capture in Fiddler but this missing request is HTTPS (it's off by default)
Your WebClient has a custom proxy configured and isn't pulling the default settings from IE

HttpWebRequest 401 error

I am developing an intranet application (Windows Authentication) which download report stream from reporting server then save it as a file. When I ran it in debuging mode it works fine。 The code is as below:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UseDefaultCredentials = true;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream fStream = response.GetResponseStream();
However after I deployed it to the server, it won't get response rather than getting 401 unauthorized error.
Even I change the code to:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string domain = ConfigurationManager.AppSettings["SchedulerDomain"];
string userName = ConfigurationManager.AppSettings["SchedulerUser"];
string passWord = ConfigurationManager.AppSettings["SchedulerPassword"];
NetworkCredential credential = new System.Net.NetworkCredential(userName, passWord, domain);
req.Credentials = credential;
HttpWebResponse response = (HttpWebResponse)req.GetResponse();
Stream fStream = response.GetResponseStream();
Get the same error. The user setup in the code has the permission to view/run the report.
The IIS7 is using Negotiate and NTLM. (Due to complicated reason, can't change Kerberos), run under ApplicationPoolIdentity
My question is, when I run it under debug mode, the user is my windows account, but why it fails when I tried to send the credential to the reporting server?
Anyone can help?
I capture all the request from the application server to the reporting server, find that all the requests' header's credential username and domain, password are null. Finally I think it is the NTLM causes the issue as here requires two credential hops which NTLM can't handle it, need use Kerberos.
There is another solution if you can't use Kerberos authentication: disable the asp.net impersonation, so from the app server to reporting server will use the applicationpoolidentity, which is a local machine account with account as such: domain/machinename$. So if you grant this account with browse permission on the reporting server, it should work.
I'm not sure how your IIS is configured but it seems like the Identity in your Application Pools setting for your app is overriding any supplied credential. Most obviously, the user that it is trying to authenticate with does not have access. That being said go to your IIS Manager and check the Identity settings for the site's Application Pool.
Change it to a user that has access to the report viewer and that should fix it. I've had a similar issue I posted here in case anyone is interested.

Authenticated HttpWebRequest with redirection, persisting credentials?

My ASP.NET 2.0 app creates a HTTPWebRequest to a site within a company's intranet, which uses NTLM authentication. The credentials passed are for a service account, which is authenticated on the domain successfully (the security log confirms this)
Some abbreviated code follows..
HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username,
pwd, domain);
req.Credentials = cred;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
As part of the request, there are a couple of redirections (within the same domain) to the final response - which is handled OK on my dev machine (Windows 2k)
When this request is created from my deployment environment (Windows 2k3), I get a 401 Unauthorized error returned from the site, seemingly after the first redirect code is returned (301 Moved), and my request object attempts to follow the redirect.
So basically, does anyone know of any issues surrounding authenticated HttpWebRequests that follow redirections?
PS - The obvious workaround is to simply request the page redirected to - but I the admins in charge of the intranet site want to monitor my app's usage by redirecting me through a specific page.
For HttpWebRequest to reuse credentials across redirects you need to use a credential cache.
If you just assign a NetworkCredentials object it will only be used on the first request.
Here is an example:
HttpWebRequest req = WebRequest.Create(queryUrl) as HttpWebRequest;
NetworkCredential cred = new NetworkCredential(username, pwd, domain);
var cache = new CredentialCache {{queryUrl, "Ntlm", cred}};
req.Credentials = cache;
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
It's going to depend on how your auth. scheme works. The Network credentials is only going to help for the NTLM part of if. I suspect that the site you are trying to access is using forms authentication also. If this is the case, when you log in you should get an auth cookie, you will need to include that in subsequent requests, e.g. after a redirect. I think the WebRequest object has a headers collection that you can use to hold the cookie. Might be a good idea to use fiddler or firebug to see what is coming across when you normally browse.
If you are using NTLM, This is the classic 2 hop problem. It works on your dev machine because the client and the server are on the same box and the credentials are passed at most once (to the redirect final target machine i'm guessing)
When you deploy to your prod environment, there are 3 machines involved. Client browser passes credentials to server1, then server1 tries to pass the credentials to server2 which is not allowed. One work around is to implement Kerberos authentication (a stricter protocol) which will allow server1 to pass credentials to server2

Get current request's credentials for using in WebRequest

When accessing my site, the user has to enter his credentials. They are basically plain directory access credentials.
At a certain point I check if a certain file they want to download exists by calling
WebRequest req = HttpWebRequest.Create(checkUri.AbsoluteUri);
WebResponse res = req.GetResponse();
Although I can access the checkUri from the browser, I get a 401 when doing the above check. I think I have to set the
req.Credentials
But I don't know where the current credentials are stored...
Any ideas?
--Update--
Integrated Windows Authentication: No
Allow Anonymous: Off
Caler: Link on page of same site (GET)
Impersonation: default is off (don't even know how to enable it in asp.net mvc)
I was having a similar problem on a site where I'm using forms authentication, I was able to solve this problem by using the code provided here as the second reply in the thread.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
// Add the current authentication cookie to the request
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
Cookie authenticationCookie = new Cookie(
FormsAuthentication.FormsCookieName,
cookie.Value,
cookie.Path,
HttpContext.Current.Request.Url.Authority);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(authenticationCookie);
WebResponse res = req.GetResponse();
I think you want this:
req.Credentials = CredentialCache.DefaultCredentials;
You're going to need to enable Integrated Windows Authentication.
I don't know what happens in ASP.NET MVC, but in ASP.NET Web Forms impersonation is turned on by:
<identity impersonate="true">
in web.config.

Resources