ojek ojek - 1 year ago 81
C# Question

Forms authentication with NetworkCredentials fails

This is what I use to authenticate myself and make an action:

var uri = new Uri(@"http://localhost:5898/forums/AddPost/1");
var request = WebRequest.Create(uri);
request.Credentials = new CredentialCache { { new Uri(@"http://localhost:5898/Account/Login"), "Basic", new NetworkCredential("asdf", "ghijkl") } };
request.Method = "POST";

const string strPost = "Content=TestAplikacji&AddedValue=0";
StreamWriter myWriter = null;

request.ContentLength = strPost.Length;
request.ContentType = "application/x-www-form-urlencoded";

string response;
myWriter = new StreamWriter(request.GetRequestStream());

if (myWriter != null) myWriter.Close();

var objResponse = (HttpWebResponse)request.GetResponse();
using (var sr = new StreamReader(objResponse.GetResponseStream()))
response = sr.ReadToEnd();

When the code executes, in the
I get validation errors for login and password. But my provided login and password (
"asdf", "ghijkl"
) are satisfying those requirements, and that means, the
is not receiving credentials that I have provided. What am I doing wrong?

Answer Source

I believe, you should use Windows authentication / Basic Authentication, if you want to use the Network credential.

For forms authentication you need to post the username and password to the page just like what a browser will do and read the authentication cookie from the response. You should be using this cookie for communicating further with authenticated pages

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download