WebRequest Credentials - c#

I am using console app to access WebApi.
I am creating WebRequest as follows:
var request = (HttpWebRequest)WebRequest.Create(url);
if (username == String.Empty)
{
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
request.Credentials = new NetworkCredential(username, password);
}
I am opening command window using:
runas /savecred /user:test_user cmd
The problem is, if a username and password is supplied, the app is still connecting as "test_user" and ignores supplied username and password.
My question is: How can I make WebRequest to use the supplied username and password?

It might be that the parameter savecred is saving the credentials. Try running this:
rundll32.exe keymgr.dll, KRShowKeyMgr
and remove "test_user". Then run your program again without savecred.

Related

HttpWebRequest Credentials stored/cached automatically?

I have an HttpWebRequest with Credentials, as seen below. This works perfectly well. However, something strange happens when I change my password on the server side: subsequent requests to the same URL are successful, even though the password is no longer valid.
This behavior continues even if I close the app completely and reopen it. Do the Credentials persist somehow? Any insight would be greatly appreciated.
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(item.Url) as HttpWebRequest;
nc = new NetworkCredential();
nc.UserName = Username;
nc.Password = Password;
request.Credentials = nc;
request.BeginGetResponse(new AsyncCallback(SubReadWebRequestCallback), request);
}

NetworkCredential working for POST but not GET

I'm calling a webAPI web service that uses windows authentication. I'm using this code in my development environment since I am developing from a box that is not on the domain.
var req = (HttpWebRequest)WebRequest.Create(url);
req.Credentials = new NetworkCredential("username", "password", "domain");
req.Method = WebRequestMethods.Http.Post; //or get
This works just fine when I do a post, but when I want to do a get it doesn't work.
When i visit the url for the get in a web browser it asks for my username and password, as expected. I enter the username and password correctly and the GET works.
Try basic authentication as below:
string credentials = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
req.Headers.Add("Authorization", authorization);

Provide Credentials for BackgroundTransferRequest (WP8)

When I am using HttpWebRequest I use the following code to set the Credentials
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToCall);
request.Method = "GET";
request.Credentials = new NetworkCredential(username, pass);
How do I do the same when I am using BackgroundTransferService in Windows Phone 8.
For reference I am using the following.
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202955%28v=vs.105%29.aspx
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202959%28v=vs.105%29.aspx
*Edit:
The authentication method is Digest
This is what I get in the Authorization Header when I use my browser to download the file.
Digest username="adf", realm="bcd", nonce="XXXXXXXXX", uri="/ans/1268e52399.txt", algorithm=MD5, response="XXXXXXXXXXXXXXX", qop=auth, nc=00000001, cnonce="XXXXXXXXXXXX"
Unfortunately this isn't supported on the BackgroundTranserService. One possible solution might be to manually create a header for your request like below:
var credentials = new UTF8Encoding().GetBytes(username + ":" +password);
var transferRequest = new BackgroundTransferRequest(transferUri);
transferRequest.Headers["Authorization"] ="Basic " + convert.ToBase64String(credentials);
Unfortunately I'm unable to test this at the minute, give it a try and let me know how you get on.

Validate domain user credentials with .NET 2

This question is solved with Framework 3.5, however I need to do this using .NET Framework 2 and C#.
I want to validate a given domain\user and password combination. For example:
Username: TheDomain\TheName
Password: ThePassword
Also note the drawbacks to the suggested solutions given in the link.
Current solution that I am using, however note the false negative possibilities
You can use NetworkCredential.Domain Property
The following code example uses the Domain property to set the domain associated with the credentials
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential("", "", "");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = password;
// Create a WebRequest with the specified URL.
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials;
Console.WriteLine("\n\nUser Credentials:- Domain: {0} , UserName: {1} , Password: {2}",
myCredentials.Domain, myCredentials.UserName, myCredentials.Password);
// Send the request and wait for a response.
Console.WriteLine("\n\nRequest to Url is sent.Waiting for response...Please wait ...");
WebResponse myWebResponse = myWebRequest.GetResponse();
// Process the response.
Console.WriteLine("\nResponse received sucessfully");
// Release the resources of the response object.
myWebResponse.Close();
Here is the MSDN Link for more reading
Hope it will help

System.Net.CredentialCache and HttpWebResponse

I'm trying coding some functionality where the user may log in into a remote server by using its own Windows Credentials or by specifying some user, password and domain.
In order to know how to do it I read this link[1].
I have been able to successfully log in via CredentialCache.DefaultCredentials.
However, whenever I try to authenticate via user, name, password and domain I keep on getting a 401 error.
After some Googling and searching here I have found some probable errors (redirecting, different auth. types {basic, digest, ntlm, negotiate} and even the case contrary [i.e. being able to login through user+pasword but no by CredentialCache.DefaultCredentials]).
Any hints?
Edit: maybe some code would give you some clues about what I am doing wrong.
static void Main(string[] args)
{
string password = "password", username = "Username", dom = "DOMAIN";
string url = "http://my.url.com/LoginWithNativeCredentials?";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
/////// Different User code////
NetworkCredential credentials = new NetworkCredential(username, password, dom);
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(url), "NTLM", credentials);
request.Credentials = cache;
/////////////////////////
////// Current Windows user's credential
//request.Credentials = CredentialCache.DefaultCredentials;
/////////////////////////
request.AllowAutoRedirect = true;
request.CookieContainer = new CookieContainer(5);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine("In!");
}
Console.WriteLine("Done!");
Console.ReadLine();
}
Many thanks!
[1] http://support.microsoft.com/kb/811318

Categories