Fallo al iniciar sesion

(1/2) > >>

Kaxperday:
No consigo iniciar sesion en esta web:

Código:

<form action="http://www.web.com/index.php/users/dologin" method="post" accept-charset="utf-8">    <p align="center"><label>Usuario</label>    <input type="text" name="usuario" value="" id="keyboard"  /></p>

    <p align="center"><label>Contraseña</label>    <input type="password" name="contrasena" value="" id="keyboard_pwd"  /></p>

    <p align="center"><input type="submit" name="submit" value="Login"  /></p>
    </form>

Estoy usando C#uso esto:

Código
public void signUp(string usuario, string contraseña)
       {
           string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
           byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);
           HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://www.web.com/index.php/users/dologin");
           req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";//utf-8;
           req.ContentType = "application/x-www-form-urlencoded";
           req.ContentLength = byteData.Length;
           req.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0";
           req.Host = "www.web.com";
           req.Method = "POST";
           req.Proxy = null;
           using (Stream reqStream = req.GetRequestStream())
               reqStream.Write(byteData, 0, byteData.Length);
           GetResponse(req);
       }
 
       private static void GetResponse(HttpWebRequest req)
       {
           HttpWebResponse response = (HttpWebResponse)req.GetResponse();
           using (Stream responseStream = response.GetResponseStream())
           {
               using (StreamReader sr = new StreamReader(responseStream))
               {
                   string responseData = sr.ReadToEnd();
                   Console.WriteLine(responseData);
                   if (responseData.Contains("Salir de"))
                       Console.WriteLine("Login successful!");
                   else
                       Console.WriteLine("Login failed!");
               }
           }
       }

¿Que puedo estar pasando por alto?, saludos y gracias.

Edito: Aporto mas informacion, el servidor me devuelve la pagina del index, si no pongo la variable usuario y la escribo mal (PE usaodi) me dice que el campo de usuario no esta rellenado, igual ocurre con la contraseña luego es algo que si que envio, pero apesar de que el nombre y usuario son correctos y consigo iniciar sesion en navegador, con el programa aun no lo he conseguido.

Saludos.

Eleкtro:
Cita de: Kaxperday en 29 Marzo 2015, 23:39 pm

¿Que puedo estar pasando por alto?, saludos y gracias.

1. ¿Te has asegurado de codificar los valores de los parámetros en caso de que contengan caracteres especiales como espacios en blanco, puntos, etc?:
Código
HttpUtility.UrlEncode(usuario);
HttpUtility.UrlEncode(contraseña);

2. ¿Has comprobado que le estás pasando las cabeceras correctas?.

3. De todas formas podrías necesitar más que eso, prueba a obtener la Cookie de visitante en la página principal, y luego a loguearte usando dicha cookie,
escribí este snippet al que se le puede dar un uso más o menos genérico que podría servir para tu situación, le hice unas pequeñas modificaciones para adaptarlo a tus necesidades, solo modifica los valores de la propiedades 'UrlMain', 'UrlLogin', 'UrlLoginQueryFormat', comprueba las cabeceras que asigno en 'RequestHeadersPostLogin' sean correctas y no falten más, y por último llama al método 'CheckLogin' para evaluar el login.

VB.Net:
Código
 
   ''' <summary>
   ''' Gets the main url.
   ''' </summary>
   ''' <value>The main url.</value>
   Public ReadOnly Property UrlMain As String
       Get
           Return "http://www.cgwallpapers.com/"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the login url.
   ''' </summary>
   ''' <value>The login url.</value>
   Public ReadOnly Property UrlLogin As String
       Get
           Return "http://www.cgwallpapers.com/login.php"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the login query string format.
   ''' </summary>
   ''' <value>The login query string format.</value>
   Public ReadOnly Property UrlLoginQueryFormat As String
       Get
           Return "usuario={0}&contrasena={1}"
       End Get
   End Property
 
   ''' <summary>
   ''' Gets the headers for a Login POST request.
   ''' </summary>
   ''' <value>The headers for a Login POST request.</value>
   Public ReadOnly Property RequestHeadersPostLogin As WebHeaderCollection
       Get
 
           Dim headers As New WebHeaderCollection
           With headers
               .Add("Accept-Language", "en-us,en;q=0.5")
               .Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7")
               .Add("Keep-Alive", "99999")
           End With
           Return headers
 
       End Get
   End Property
 
   ''' <summary>
   ''' Determines whether the user is logged in the site.
   ''' </summary>
   Private isLogged As Boolean
 
   ''' <summary>
   ''' Gets the cookie container.
   ''' </summary>
   ''' <value>The cookie container.</value>
   Public ReadOnly Property CookieCollection As CookieCollection
       Get
           Return Me.cookieCollection1
       End Get
   End Property
   ''' <summary>
   ''' The cookie container.
   ''' </summary>
   Private cookieCollection1 As CookieCollection
 
   ''' <summary>
   ''' Defines the query data for a LoginPost request.
   ''' </summary>
   Private NotInheritable Class LoginQueryData
 
       ''' <summary>
       ''' Gets the Usuario field.
       ''' </summary>
       ''' <value>The Usuario field.</value>
       Public Property Usuario As String
 
       ''' <summary>
       ''' Gets or sets the Conteasena field.
       ''' </summary>
       ''' <value>The Conteasena field.</value>
       Public Property Contrasena As String
 
   End Class
 
   ''' <summary>
   ''' Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
   ''' </summary>
   ''' <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
   ''' <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
   Private Function GetLoginQueryString(ByVal loginQueryData As LoginQueryData) As String
 
       Return String.Format(Me.UrlLoginQueryFormat,
                            loginQueryData.Usuario,
                            loginQueryData.Contrasena)
 
   End Function
 
   ''' <summary>
   ''' Sets the cookie container.
   ''' </summary>
   ''' <param name="url">The url.</param>
   ''' <param name="cookieCollection">The cookie collection.</param>
   ''' <returns>CookieContainer.</returns>
   Private Function SetCookieContainer(ByVal url As String,
                                       ByVal cookieCollection As CookieCollection) As CookieContainer
 
       Dim cookieContainer As New CookieContainer
       Dim refDate As Date
 
       For Each oldCookie As Cookie In cookieCollection
 
           If Not DateTime.TryParse(oldCookie.Value, refDate) Then
 
               Dim newCookie As New Cookie
               With newCookie
                   .Name = oldCookie.Name
                   .Value = oldCookie.Value
                   .Domain = New Uri(url).Host
                   .Secure = False
               End With
 
               cookieContainer.Add(newCookie)
 
           End If
 
       Next oldCookie
 
       Return cookieContainer
 
   End Function
 
   ''' <summary>
   ''' Converts cookie string to global cookie collection object.
   ''' </summary>
   ''' <param name="cookie">The cookie string.</param>
   ''' <param name="cookieCollection">The cookie collection.</param>
   Private Sub SaveCookies(ByVal cookie As String,
                           ByRef cookieCollection As CookieCollection)
 
       Dim cookieStrings() As String = cookie.Trim.
                                              Replace("path=/,", String.Empty).
                                              Replace("path=/", String.Empty).
                                              Split({";"c}, StringSplitOptions.RemoveEmptyEntries)
 
       cookieCollection = New CookieCollection
 
       For Each cookieString As String In cookieStrings
 
           If Not String.IsNullOrEmpty(cookieString.Trim) Then
 
               cookieCollection.Add(New Cookie(name:=cookieString.Trim.Split("="c)(0),
                                               value:=cookieString.Trim.Split("="c)(1)))
 
           End If
 
       Next cookieString
 
   End Sub
 
   ''' <summary>
   ''' Convert cookie container object to global cookie collection object.
   ''' </summary>
   ''' <param name="cookieContainer">The cookie container.</param>
   ''' <param name="cookieCollection">The cookie collection.</param>
   ''' <param name="url">The url.</param>
   Private Sub SaveCookies(ByVal cookieContainer As CookieContainer,
                           ByRef cookieCollection As CookieCollection,
                           ByVal url As String)
 
       cookieCollection = New CookieCollection
 
       For Each cookie As Cookie In cookieContainer.GetCookies(New Uri(url))
 
           cookieCollection.Add(cookie)
 
       Next cookie
 
   End Sub
 
   ''' <param name="url">The url.</param>
   ''' <param name="cookieCollection">The cookie collection.</param>
   ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
   Private Function GetMethod(ByVal url As String,
                              ByRef cookieCollection As CookieCollection) As Boolean
 
       Debug.WriteLine("[+] GetMethod function started.")
 
       Dim request As HttpWebRequest = Nothing
       Dim response As HttpWebResponse = Nothing
       Dim sr As StreamReader = Nothing
       Dim result As Boolean = False
 
       Try
           Debug.WriteLine("[+] Attempting to perform a request with:")
           Debug.WriteLine(String.Format("Method: {0}", "GET"))
           Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
 
           request = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
           With request
               .Method = "GET"
               .Headers = Me.RequestHeadersPostLogin
               .Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
               .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
               .AllowAutoRedirect = False
               .KeepAlive = True
           End With
           Debug.WriteLine("[-] Request done.")
 
           ' Get the server response.
           Debug.WriteLine("[+] Getting server response...")
           response = DirectCast(request.GetResponse, HttpWebResponse)
           Debug.WriteLine("[-] Getting server response done.")
 
           If request.HaveResponse Then
 
               ' Save the cookie info.
               Debug.WriteLine("[+] Saving cookies...")
               Me.SaveCookies(response.Headers("Set-Cookie"), cookieCollection)
               Debug.WriteLine("[-] Saving cookies done.")
 
               ' Get the server response.
               Debug.WriteLine("[+] Getting server response...")
               response = DirectCast(request.GetResponse, HttpWebResponse)
               Debug.WriteLine("[-] Getting server response done.")
 
               Debug.WriteLine("[+] Reading server response...")
               sr = New StreamReader(response.GetResponseStream)
               Using sr
                   ' Read the response from the server, but we do not save it.
                   sr.ReadToEnd()
               End Using
               result = True
               Debug.WriteLine("[-] Reading server response done.")
 
           Else ' No response received from server.
               Throw New Exception(String.Format("No response received from server with url: {0}", url))
               result = False
 
           End If
 
       Catch ex As Exception
           Throw
           result = False
 
       Finally
           If sr IsNot Nothing Then
               sr.Dispose()
           End If
           If response IsNot Nothing Then
               response.Close()
           End If
 
       End Try
 
       Debug.WriteLine("[-] GetMethod function finished.")
       Debug.WriteLine("[i] Returning result value...")
       Return result
 
   End Function
 
   ''' <param name="loginData">The login post data.</param>
   ''' <param name="cookieCollection">The cookie collection.</param>
   ''' <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
   Private Function PostLoginMethod(ByVal loginData As LoginQueryData,
                                    ByRef cookieCollection As CookieCollection) As Boolean
 
       Debug.WriteLine("[+] PostLoginMethod function started.")
 
       Dim request As HttpWebRequest = Nothing
       Dim response As HttpWebResponse = Nothing
       Dim sw As StreamWriter = Nothing
       Dim initialCookieCount As Integer = 0
       Dim postData As String
       Dim result As Boolean = False
 
       Try
           Debug.WriteLine("[+] Attempting to perform a login request with:")
           Debug.WriteLine(String.Format("Method: {0}", "POST"))
           Debug.WriteLine(String.Format("Referer: {0}", Me.UrlMain))
           Debug.WriteLine(String.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"))
           Debug.WriteLine(String.Format("ContentType: {0}", "application/x-www-form-urlencoded"))
           Debug.WriteLine(String.Format("Headers: {0}", String.Join(Environment.NewLine, Me.RequestHeadersPostLogin)))
 
           request = DirectCast(HttpWebRequest.Create(Me.UrlLogin), HttpWebRequest)
           With request
               .Method = "POST"
               .Headers = Me.RequestHeadersPostLogin
               .Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
               .ContentType = "application/x-www-form-urlencoded"
               .UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0"
               .Referer = Me.UrlMain
           End With
           Debug.WriteLine("[-] Request done.")
 
           Debug.WriteLine("[+] Passing request cookie info...")
           If cookieCollection IsNot Nothing Then ' Pass cookie info from the login page.
               request.CookieContainer = Me.SetCookieContainer(Me.UrlLogin, cookieCollection)
           End If
           Debug.WriteLine("[-] Passing request cookie info done.")
 
           ' Set the post data.
           Debug.WriteLine("[+] Setting post data with:")
           Debug.WriteLine(String.Format("Usuario: {0}", loginData.Usuario))
           Debug.WriteLine(String.Format("Contrasena: {0}", loginData.Contrasena))
           postData = Me.GetLoginQueryString(loginData)
 
           sw = New StreamWriter(request.GetRequestStream)
           Using sw
               sw.Write(postData) ' Post the data to the server.
           End Using
           Debug.WriteLine("[-] Setting post data done.")
 
           ' Get the server response.
           Debug.WriteLine("[+] Getting server response...")
           initialCookieCount = request.CookieContainer.Count
           response = DirectCast(request.GetResponse, HttpWebResponse)
           Debug.WriteLine("[-] Getting server response done.")
 
           If request.CookieContainer.Count > initialCookieCount Then ' Login successful.
               result = True
 
           Else ' Login unsuccessful.
               result = False
 
           End If
 
           Debug.WriteLine(String.Format("[i] Login response result is: {0}",
                                         If(result, "Successful (True)",
                                                    "Unsuccessful (False)")))
 
           If result Then ' Save new login cookies.
               Debug.WriteLine("[+] Saving new login cookies...")
               Me.SaveCookies(request.CookieContainer, cookieCollection, Me.UrlMain)
               Debug.WriteLine("[-] Saving new login cookies done.")
           End If
 
       Catch ex As Exception
           Throw
 
       Finally
           If sw IsNot Nothing Then
               sw.Dispose()
           End If
           If response IsNot Nothing Then
               response.Close()
           End If
 
       End Try
 
       Debug.WriteLine("[-] PostLoginMethod function finished.")
       Debug.WriteLine("[i] Returning result value...")
       Me.isLogged = result
       Return result
 
   End Function
 
   ''' <summary>
   ''' Determines whether the account can log in CGWallpapers site.
   ''' </summary>
   ''' <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
   Public Function CheckLogin(ByVal username As String,
                              ByVal password As String) As Boolean
 
       If Me.GetMethod(Me.UrlMain, Me.cookieCollection1) Then
 
           Dim loginQueryData As New LoginQueryData With
                 {
                     .Usuario = HttpUtility.UrlEncode(username),
                     .Contrasena = HttpUtility.UrlEncode(password)
                 }
           Return Me.PostLoginMethod(loginQueryData, Me.cookieCollection1)
 
       Else
           Return False
 
       End If ' Me.GetMethod
 
   End Function
 

Traducción online a C# (sin testear):
Código
/// <summary>
/// Gets the main url.
/// </summary>
/// <value>The main url.</value>
public string UrlMain {
get { return "http://www.cgwallpapers.com/"; }
}
 
/// <summary>
/// Gets the login url.
/// </summary>
/// <value>The login url.</value>
public string UrlLogin {
get { return "http://www.cgwallpapers.com/login.php"; }
}
 
/// <summary>
/// Gets the login query string format.
/// </summary>
/// <value>The login query string format.</value>
public string UrlLoginQueryFormat {
get { return "usuario={0}&contrasena={1}"; }
}
 
/// <summary>
/// Gets the headers for a Login POST request.
/// </summary>
/// <value>The headers for a Login POST request.</value>
public WebHeaderCollection RequestHeadersPostLogin {
 
get {
WebHeaderCollection headers = new WebHeaderCollection();
var _with1 = headers;
_with1.Add("Accept-Language", "en-us,en;q=0.5");
_with1.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
_with1.Add("Keep-Alive", "99999");
return headers;
 
}
}
 
/// <summary>
/// Determines whether the user is logged in the site.
/// </summary>
 
private bool isLogged;
/// <summary>
/// Gets the cookie container.
/// </summary>
/// <value>The cookie container.</value>
public CookieCollection CookieCollection {
get { return this.cookieCollection1; }
}
/// <summary>
/// The cookie container.
/// </summary>
 
private CookieCollection cookieCollection1;
/// <summary>
/// Defines the query data for a LoginPost request.
/// </summary>
private sealed class LoginQueryData
{
 
/// <summary>
/// Gets the Usuario field.
/// </summary>
/// <value>The Usuario field.</value>
public string Usuario { get; set; }
 
/// <summary>
/// Gets or sets the Conteasena field.
/// </summary>
/// <value>The Conteasena field.</value>
public string Contrasena { get; set; }
 
}
 
/// <summary>
/// Gets a formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.
/// </summary>
/// <param name="loginQueryData">The <see cref="LoginQueryData"/> object that contains the login query fields.</param>
/// <returns>A formatted <see cref="String"/> representation of a <see cref="LoginQueryData"/> object.</returns>
private string GetLoginQueryString(LoginQueryData loginQueryData)
{
 
return string.Format(this.UrlLoginQueryFormat, loginQueryData.Usuario, loginQueryData.Contrasena);
 
}
 
/// <summary>
/// Sets the cookie container.
/// </summary>
/// <param name="url">The url.</param>
/// <param name="cookieCollection">The cookie collection.</param>
/// <returns>CookieContainer.</returns>
private CookieContainer SetCookieContainer(string url, CookieCollection cookieCollection)
{
 
CookieContainer cookieContainer = new CookieContainer();
System.DateTime refDate = default(System.DateTime);
 
 
foreach (Cookie oldCookie in cookieCollection) {
 
if (!DateTime.TryParse(oldCookie.Value, refDate)) {
Cookie newCookie = new Cookie();
var _with2 = newCookie;
_with2.Name = oldCookie.Name;
_with2.Value = oldCookie.Value;
_with2.Domain = new Uri(url).Host;
_with2.Secure = false;
 
cookieContainer.Add(newCookie);
 
}
 
}
 
return cookieContainer;
 
}
 
/// <summary>
/// Converts cookie string to global cookie collection object.
/// </summary>
/// <param name="cookie">The cookie string.</param>
/// <param name="cookieCollection">The cookie collection.</param>
 
private void SaveCookies(string cookie, ref CookieCollection cookieCollection)
{
string[] cookieStrings = cookie.Trim.Replace("path=/,", string.Empty).Replace("path=/", string.Empty).Split({ ';' }, StringSplitOptions.RemoveEmptyEntries);
 
cookieCollection = new CookieCollection();
 
 
foreach (string cookieString in cookieStrings) {
 
if (!string.IsNullOrEmpty(cookieString.Trim)) {
cookieCollection.Add(new Cookie(name: cookieString.Trim.Split('=')(0), value: cookieString.Trim.Split('=')(1)));
 
}
 
}
 
}
 
/// <summary>
/// Convert cookie container object to global cookie collection object.
/// </summary>
/// <param name="cookieContainer">The cookie container.</param>
/// <param name="cookieCollection">The cookie collection.</param>
/// <param name="url">The url.</param>
 
private void SaveCookies(CookieContainer cookieContainer, ref CookieCollection cookieCollection, string url)
{
cookieCollection = new CookieCollection();
 
 
foreach (Cookie cookie in cookieContainer.GetCookies(new Uri(url))) {
cookieCollection.Add(cookie);
 
}
 
}
 
/// <param name="url">The url.</param>
/// <param name="cookieCollection">The cookie collection.</param>
/// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
private bool GetMethod(string url, ref CookieCollection cookieCollection)
{
 
Debug.WriteLine("[+] GetMethod function started.");
 
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamReader sr = null;
bool result = false;
 
try {
Debug.WriteLine("[+] Attempting to perform a request with:");
Debug.WriteLine(string.Format("Method: {0}", "GET"));
Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
 
request = (HttpWebRequest)HttpWebRequest.Create(url);
var _with3 = request;
_with3.Method = "GET";
_with3.Headers = this.RequestHeadersPostLogin;
_with3.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
_with3.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
_with3.AllowAutoRedirect = false;
_with3.KeepAlive = true;
Debug.WriteLine("[-] Request done.");
 
// Get the server response.
Debug.WriteLine("[+] Getting server response...");
response = (HttpWebResponse)request.GetResponse;
Debug.WriteLine("[-] Getting server response done.");
 
 
if (request.HaveResponse) {
// Save the cookie info.
Debug.WriteLine("[+] Saving cookies...");
this.SaveCookies(response.Headers("Set-Cookie"), ref cookieCollection);
Debug.WriteLine("[-] Saving cookies done.");
 
// Get the server response.
Debug.WriteLine("[+] Getting server response...");
response = (HttpWebResponse)request.GetResponse;
Debug.WriteLine("[-] Getting server response done.");
 
Debug.WriteLine("[+] Reading server response...");
sr = new StreamReader(response.GetResponseStream);
using (sr) {
// Read the response from the server, but we do not save it.
sr.ReadToEnd();
}
result = true;
Debug.WriteLine("[-] Reading server response done.");
 
// No response received from server.
} else {
throw new Exception(string.Format("No response received from server with url: {0}", url));
result = false;
 
}
 
} catch (Exception ex) {
throw;
result = false;
 
} finally {
if (sr != null) {
sr.Dispose();
}
if (response != null) {
response.Close();
}
 
}
 
Debug.WriteLine("[-] GetMethod function finished.");
Debug.WriteLine("[i] Returning result value...");
return result;
 
}
 
/// <param name="loginData">The login post data.</param>
/// <param name="cookieCollection">The cookie collection.</param>
/// <returns><c>true</c> if successfull, <c>false</c> otherwise.</returns>
private bool PostLoginMethod(LoginQueryData loginData, ref CookieCollection cookieCollection)
{
 
Debug.WriteLine("[+] PostLoginMethod function started.");
 
HttpWebRequest request = null;
HttpWebResponse response = null;
StreamWriter sw = null;
int initialCookieCount = 0;
string postData = null;
bool result = false;
 
try {
Debug.WriteLine("[+] Attempting to perform a login request with:");
Debug.WriteLine(string.Format("Method: {0}", "POST"));
Debug.WriteLine(string.Format("Referer: {0}", this.UrlMain));
Debug.WriteLine(string.Format("Accept: {0}", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
Debug.WriteLine(string.Format("ContentType: {0}", "application/x-www-form-urlencoded"));
Debug.WriteLine(string.Format("Headers: {0}", string.Join(Environment.NewLine, this.RequestHeadersPostLogin)));
 
request = (HttpWebRequest)HttpWebRequest.Create(this.UrlLogin);
var _with4 = request;
_with4.Method = "POST";
_with4.Headers = this.RequestHeadersPostLogin;
_with4.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_with4.ContentType = "application/x-www-form-urlencoded";
_with4.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0";
_with4.Referer = this.UrlMain;
Debug.WriteLine("[-] Request done.");
 
Debug.WriteLine("[+] Passing request cookie info...");
// Pass cookie info from the login page.
if (cookieCollection != null) {
request.CookieContainer = this.SetCookieContainer(this.UrlLogin, cookieCollection);
}
Debug.WriteLine("[-] Passing request cookie info done.");
 
// Set the post data.
Debug.WriteLine("[+] Setting post data with:");
Debug.WriteLine(string.Format("Usuario: {0}", loginData.Usuario));
Debug.WriteLine(string.Format("Contrasena: {0}", loginData.Contrasena));
postData = this.GetLoginQueryString(loginData);
 
sw = new StreamWriter(request.GetRequestStream);
using (sw) {
sw.Write(postData);
// Post the data to the server.
}
Debug.WriteLine("[-] Setting post data done.");
 
// Get the server response.
Debug.WriteLine("[+] Getting server response...");
initialCookieCount = request.CookieContainer.Count;
response = (HttpWebResponse)request.GetResponse;
Debug.WriteLine("[-] Getting server response done.");
 
// Login successful.
if (request.CookieContainer.Count > initialCookieCount) {
result = true;
 
// Login unsuccessful.
} else {
result = false;
 
}
 
Debug.WriteLine(string.Format("[i] Login response result is: {0}", result ? "Successful (True)" : "Unsuccessful (False)"));
 
// Save new login cookies.
if (result) {
Debug.WriteLine("[+] Saving new login cookies...");
this.SaveCookies(request.CookieContainer, ref cookieCollection, this.UrlMain);
Debug.WriteLine("[-] Saving new login cookies done.");
}
 
} catch (Exception ex) {
throw;
 
} finally {
if (sw != null) {
sw.Dispose();
}
if (response != null) {
response.Close();
}
 
}
 
Debug.WriteLine("[-] PostLoginMethod function finished.");
Debug.WriteLine("[i] Returning result value...");
this.isLogged = result;
return result;
 
}
 
 
/// <summary>
/// Determines whether the account can log in CGWallpapers site.
/// </summary>
/// <returns><c>true</c> if the account can log in CGWallpapers site, <c>false</c> otherwise.</returns>
public bool CheckLogin(string username, string password)
{
 
 
if (this.GetMethod(this.UrlMain, this.cookieCollection1)) {
LoginQueryData loginQueryData = new LoginQueryData {
Usuario = HttpUtility.UrlEncode(username),
Contrasena = HttpUtility.UrlEncode(password)
};
return this.PostLoginMethod(loginQueryData, this.cookieCollection1);
 
} else {
return false;
 
}
// Me.GetMethod
 
}
 
//=======================================================
//Service provided by Telerik (www.telerik.com)
//=======================================================

Kaxperday:
Hola elektro gracias por la respuesta, las variables si que estan codificadas:

Código
string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
           byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);

He mirado con wireshark lo que mando y parece estar todo correcto el tamaño de cadena, todo.

Funciona bien pero sigo sin saber porque no logea, porque no me devuelve esa página una vez iniciada la sesión.

Saludos.

Eleкtro:
Cita de: Kaxperday en 31 Marzo 2015, 20:22 pm

las variables si que estan codificadas:

Código
string postData = "usuario=" + usuario + "&contrasena=" + contraseña + "&submit=Login";
           byte[] byteData = ASCIIEncoding.ASCII.GetBytes(postData);


Por codificar me refiero a la codificación html, no a codificar el string en una secuencia de bytes cómo estás haciendo.

Si el usuario/contraseña contiene por ejemplo un espacio entonces vas a codificar 1 byte " " en lugar de codificar los caracteres "%20", ¿me entiendes?.

Porfavor, aclara si el usuario/contraseña contienen espacios u otros caracteres ilegales para descartar que ese sea el problema,
si tienes dudas vuelve a leer la pregunta nº1 que hice en el comentario anterior donde mostré un ejemplo de cómo codificar el string (primero codificas el usuario/contraseña a html, y luego generas los bytes cómo estabas haciendo, pero con el usuario/contraseña codificados a html).

Saludos!

Kaxperday:
Hola socio no creo que sea problema, la cadena que mando en el POST detectada por el wireshark es la siguiente:

usuario=ASJDIAJI&contrasena=AKJDFIAJIFJ&submit=Login

Son solo mayúsculas ni espacios ni carácteres extraños, no creo que radique ahí el problema, pero se puede investigar más.

Gracias y un saludo.

Navegación

[0] Índice de Mensajes

[#] Página Siguiente