Login from external site (ASP.NET MVC 3.0)

  • Thread starter Thread starter JoseLRS
  • Start date Start date
J

JoseLRS

Guest
Hi all,

My case is: I have two sites, one with access to customers (private) and a public. I need to be able to login from the public to the private site. To do this I added the appropriate fields (user and password) and I send it with a POST operation to the private site as follows:

CookieContainer cookies = new CookieContainer();

//Request login page to get a session cookie
GETHtml(returnUrl, cookies, returnUrl);

//Now we can do login
Login(model.UserName, model.Password, cookies, returnUrl);
return Redirect(@"http://privada/");
public string GETHtml(string url, CookieContainer cookies, string returnUrl)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.CookieContainer = cookies;
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.21022;";
webRequest.Referer = returnUrl;

using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
//We need to add any response cookies to our cookie container
cookies.Add(webResponse.Cookies);

using (var stream = new StreamReader(webResponse.GetResponseStream()))
return stream.ReadToEnd();
}
}


public bool Login(string Username, string Password, CookieContainer cookies, string returnUrl)
{
string poststring = string.Format("UserName={0}&Password={1}&btn-acceder.x=63&btn-acceder.y=13&btn-acceder=login",
Username, Password);
byte[] postdata = Encoding.UTF8.GetBytes(poststring);

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(returnUrl);
webRequest.CookieContainer = cookies;
webRequest.Method = "POST";
webRequest.Referer = returnUrl;
webRequest.Headers.Add("origin", @"http://privada/");
webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.21022;";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postdata.Length;
using (Stream writer = webRequest.GetRequestStream())
writer.Write(postdata, 0, postdata.Length);

using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
//We need to add any response cookies to our cookie container
cookies.Add(webResponse.Cookies);

//Only for debug
using (var stream = new StreamReader(webResponse.GetResponseStream()))
System.Diagnostics.Debug.WriteLine(stream.ReadToEnd());

return (webResponse.StatusCode == HttpStatusCode.OK);
}
}

However, the session does not appear with private Web access. Does anyone know what Im doing wrong or can guide me?

I am using ASP.Net MVC 3.0

Thank you very much in advance,

Jose

Continue reading...
 
Back
Top