ojek ojek - 21 days ago 8
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;
try
{
myWriter = new StreamWriter(request.GetRequestStream());
myWriter.Write(strPost);
}
catch
{

}
finally
{
if (myWriter != null) myWriter.Close();
}

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


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

Answer

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