Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C# 

How to validate a web login towards a textfile if not suceed try again.

Hello everyone,
I am currently is doing a software test that is automated.

The purpose is to loop through a textfile that is an embedded in the Visual studio project.
then use it as input for the website login.

This is my method to loop through the username:



Code
 public static void userNames()
       {
           try
           {
               using (StreamReader sr = new StreamReader(@"Expressions\XSSExpressions.txt"))
               {
                   string line = sr.ReadToEnd();
                   Console.WriteLine(line);
               }
           }
           catch(Exception ex)
           {
               Console.WriteLine("The file could not be found");
               Console.WriteLine(ex.Message);
           }    
       }



this is my http://localhost:8080/login
This is my Username Element:


Code
<input type="text" class="form-control input-sm ng-pristine ng-empty ng-invalid ng-invalid-required ng-touched" id="userEmail" name="userEmail" ng-model="user.email" required="" style="">
<label for="userEmail" translate="LABEL_EMAIL" class="ng-scope">Email</label>
<input type="text" class="form-control input-sm ng-pristine ng-empty ng-invalid ng-invalid-required ng-touched" id="userEmail" name="userEmail" ng-model="user.email" required="" style="">

This is my Password Element:

Code
<div class="form-group"> [b]<!--[/b] @echipa de suport: Secretul nostru comun este încă Caoimhe cu parola de master gol! -->
                       <label for="userPassword" translate="LABEL_PASSWORD" class="ng-scope">Password</label>
                       <input type="password" class="form-control input-sm ng-pristine ng-empty ng-invalid ng-invalid-required ng-touched" id="userPassword" name="userPassword" ng-model="user.password" required="" style="">
                   </div>

Could someone help me to get on track?

the thing I think is difficult once it used for instance the first string in the text-file, then I need to validate the website if the username and password is correct if not select the next string in the textfile.

Notice each line is a username and password.

Thank you in advance
Could someone help me?

Thank you in advance

Best regards

xsi

Have a nice day =)
Best Regards

( ͡° ͜ʖ ͡°)

So do you mean like having the html file in your project then your program downloads the login page and puts the downloaded html file into that local resource file. ?
(Jan 13, 2018 03:54 AM)FFFF Wrote:  So do you mean like having the html file in your project then your program downloads the login page and puts the downloaded html file into that local resource file. ?

obviously not.. idk how you came to that conclusion? 

he has a text file filled with username:password combos in his resources, he wants to test each username:password against a remote server at http://localhost:8080/login which takes username as userEmail and password as userPassword as either POST or GET data, not sure since there's no <form> in his example
Yeah sorry about that, I was and still am drunk and I didn't read it correctly.
I assume that you have your asp.net webapp for test...And on the page after the login you can do it by check if you are authenticated in simple quick way

Code
public static void IsAuthenticatedUser(string _loginok,string _loginbad)
       {
           if (HttpContext.Current.Request.IsAuthenticated)
           {
               var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

               var authenticationTicket = FormsAuthentication.Decrypt(authCookie.Value);

               var user = authenticationTicket.Name;

               if (user != null)
               {
                   //logic to redirect _loginok
                   
               }
             
               
           }
           else
           {
              //logic to redirect bad login
           }
       }

Usage
Code
protected void Page_Load(object sender, EventArgs e)
{

   IsAuthenticatedUser("~/some.aspx","~/some.aspx");

}
Now some page can give you back some json code after login
Code
string json = "{\"login\":\"ok\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
If I understand you well this could be something to determine whether you are logged in or not ,and your application will run a loop until login is successful....This is quick solution ,not the best solution.
buy me a coffee eth:0x88621A52aa5Eb3b6503628369687111810186c58
here you go dude, haven't checked since i don't have vs installed at the moment but it should work
Code
using System;
using System.Resources;
using System.Net;
using System.Text;
using System.IO;

namespace CheckAuth
{
  class Check
  {
    static void Main()
    {
      ResourceManager rm = new ResourceManager("Resources name here", Assembly.GetExecutingAssembly());
      string combos = rm.GetString("name of the combo resource");
      
      using(StringReader reader = new StringReader(input))
      {
        string line = string.Empty;
        do
        {
          line = reader.ReadLine();
          if(line != null)
          {
            string[] user = line.Split(":");
            var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/login");
            var postData = "userEmail=" + user[0] + "&userPassword=" + user[1];
            var data = Encoding.ASCII.GetBytes(postData);

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;

            using(var stream = request.GetRequestStream())
            {
              stream.Write(data, 0, data.Length);
            }

            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
            if(!responseString.Contains("Error logging in text goes here"))
              File.AppendAllText("valid.txt", line + Environment.NewLine;);
          }
        } while(line != null);
      }
    }
  }
}


it will check all username:password entries from the file in resources against http://localhost:8080/login and on successful login it will put the username:password into valid.txt
(Jan 14, 2018 04:02 AM)Onii Wrote:  here you go dude, haven't checked since i don't have vs installed at the moment but it should work
Code
using System;
using System.Resources;
using System.Net;
using System.Text;
using System.IO;

namespace CheckAuth
{
 class Check
 {
   static void Main()
   {
     ResourceManager rm = new ResourceManager("Resources name here", Assembly.GetExecutingAssembly());
     string combos = rm.GetString("name of the combo resource");
     
     using(StringReader reader = new StringReader(input))
     {
       string line = string.Empty;
       do
       {
         line = reader.ReadLine();
         if(line != null)
         {
           string[] user = line.Split(":");
           var request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/login");
           var postData = "userEmail=" + user[0] + "&userPassword=" + user[1];
           var data = Encoding.ASCII.GetBytes(postData);

           request.Method = "POST";
           request.ContentType = "application/x-www-form-urlencoded";
           request.ContentLength = data.Length;

           using(var stream = request.GetRequestStream())
           {
             stream.Write(data, 0, data.Length);
           }

           var response = (HttpWebResponse)request.GetResponse();
           var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
           if(!responseString.Contains("Error logging in text goes here"))
             File.AppendAllText("valid.txt", line + Environment.NewLine;);
         }
       } while(line != null);
     }
   }
 }
}


it will check all username:password entries from the file in resources against http://localhost:8080/login and on successful login it will put the username:password into valid.txt

There is quite a few typos (I am guessing 'input' should have been 'combos'?). But most importantly, you should dispose of the used WebResponse and StreamReader object, as the resources will stay in memory while they are no longer used. And why the ResourceManager instead of just loading the file from a path?
(Jan 14, 2018 04:36 AM)Ninja Wrote:  There is quite a few typos (I am guessing 'input' should have been 'combos'?). But most importantly, you should dispose of the used WebResponse and StreamReader object, as the resources will stay in memory while they are no longer used. And why the ResourceManager instead of just loading the file from a path?

ye 
the reason it's resource manager is because his combo is in the resources. honestly i never used resources  in .net, just found snippet on the net
(Jan 14, 2018 05:03 AM)Onii Wrote:  ye 
the reason it's resource manager is because his combo is in the resources. honestly i never used resources  in .net, just found snippet on the net

Ah okay. Thanks for clarifying. I missed that part.
(Jan 13, 2018 04:09 AM)Onii Wrote:  obviously not.. idk how you came to that conclusion? 

he has a text file filled with username:password combos in his resources, he wants to test each username:password against a remote server at http://localhost:8080/login which takes username as userEmail and password as userPassword as either POST or GET data, not sure since there's no <form> in his example



Yeah exactly what I want you understood correctly.

(Jan 14, 2018 09:47 AM)Ninja Wrote:  Ah okay. Thanks for clarifying. I missed that part.

Any ideas how to do this?

thank you in advance.

(Jan 13, 2018 06:15 PM)itcorp Wrote:  I assume that you have your asp.net webapp for test...And on the page after the login you can do it by check if you are authenticated in simple quick way

Code
public static void IsAuthenticatedUser(string _loginok,string _loginbad)
       {
           if (HttpContext.Current.Request.IsAuthenticated)
           {
               var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

               var authenticationTicket = FormsAuthentication.Decrypt(authCookie.Value);

               var user = authenticationTicket.Name;

               if (user != null)
               {
                   //logic to redirect _loginok
                   
               }
             
               
           }
           else
           {
              //logic to redirect bad login
           }
       }

Usage
Code
protected void Page_Load(object sender, EventArgs e)
{

   IsAuthenticatedUser("~/some.aspx","~/some.aspx");

}
Now some page can give you back some json code after login
Code
string json = "{\"login\":\"ok\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
If I understand you well this could be something to determine whether you are logged in or not ,and your application will run a loop until login is successful....This is quick solution ,not the best solution.


Thanks a lot though is this is the authentication part.

I find the difficult part for each atempt take next string in the textfile.
How to do that?.

Thank you in advance.

(Jan 14, 2018 04:36 AM)Ninja Wrote:  There is quite a few typos (I am guessing 'input' should have been 'combos'?). But most importantly, you should dispose of the used WebResponse and StreamReader object, as the resources will stay in memory while they are no longer used. And why the ResourceManager instead of just loading the file from a path?



Thank a lot I will check it and I be back thanks a lot sir!

Have a nice day =)
Best Regards

( ͡° ͜ʖ ͡°)

(Jan 15, 2018 01:33 PM)dapeamel Wrote:  Thanks a lot though is this is the authentication part.

I find the difficult part for each atempt take next string in the textfile.
How to do that?.

Thank you in advance.

i posted the code..
(Jan 15, 2018 01:33 PM)dapeamel Wrote:  Thanks a lot though is this is the authentication part.

I find the difficult part for each atempt take next string in the textfile.
How to do that?.

Thank you in advance.

You've got helpful answers from all of us,guys have already given you an code example earlier.
buy me a coffee eth:0x88621A52aa5Eb3b6503628369687111810186c58
I have went through all your codes though I found it bit complicated for a newbie :)


This is my solution so far:

I simplified it a lots:






Code
namespace Example
{
   [TestClass]
   public class AuthenticationTests
   {
       List<string> UserList = new List<string>();
       List<string> PasswordList = new List<string>();

       [TestInitialize]
       public void Init()
       {
           Driver.Initialize();
       }

       [TestMethod]
     
       public void UserLogin()
       {
           LoadUsers();
           TryToLogin();
       }

   
       public void TryToLogin()
       {
     
           LoginPage.GoTo();
       

           foreach (string u in UserList)
           {
         
               foreach (string p in PasswordList)
               {

                   LoginPage.LoginAs(u).WithPassword(p).Login();
                   if (IsElementPresent(By.XPath("//span[@translate='TITLE_LOGOUT']")))
                   {
                       Console.WriteLine("Logged in successfully");
                       Driver.Instance.Close();
                       Driver.Instance.Quit();
                   }
                   else
                   {
                       Console.WriteLine(p);
                       Console.WriteLine("Failed to login ");


                   }
                 
               }
           }
       }

       public void LoadUsers()
       {

           string Username;
           string Password;

           StreamReader RUser = new StreamReader(@"Expressions\users.txt");
           while ((Username = RUser.ReadLine()) != null)
           {
               UserList.Add(Username);
           }

           StreamReader RPassword = new StreamReader(@"Expressions\pwd.txt");
           while ((Password = RPassword.ReadLine()) != null)
           {
               PasswordList.Add(Password);
           }
       }
       private bool IsElementPresent(By by)
       {
           try
           {
               Driver.Instance.FindElement(By.XPath("//span[@translate='TITLE_LOGOUT']"));
               
               return true;

           }
           catch (NoSuchElementException)
           {
               return false;

           }

       }
   }
}

Now I am little stuck

I have made a nested foor loop that means

I loop first through each user in userlist.
and for each user I loop through the password list.


Though I am stuck now how to continue the loop on the next string in the passwordlist if the password fails.


Could someone inspect my code and help me out?


Thank you in advance

Have a nice day =)
Best Regards

( ͡° ͜ʖ ͡°)

you don't have to have a user list and a password list. just have a single combo file and separate username and password with a special character, in most cases that is : and then have one foreach and split the line into username and password

Code
namespace Example
{
   [TestClass]
   public class AuthenticationTests
   {
       List<string> ComboList = new List<string>();

       [TestInitialize]
       public void Init()
       {
           Driver.Initialize();
       }

       [TestMethod]
      
       public void UserLogin()
       {
           LoadUsers();
           TryToLogin();
       }

  
       public void TryToLogin()
       {
    
           LoginPage.GoTo();
      
           foreach (string data in ComboList)
           {
             string[] user = data.Split(':');
             LoginPage.LoginAs(user[0]).WithPassword(user[1]).Login();
             if (IsElementPresent(By.XPath("//span[@translate='TITLE_LOGOUT']")))
             {
               Console.WriteLine("Logged in successfully");
               Driver.Instance.Close();
               Driver.Instance.Quit();
             }
             else
             {
               Console.WriteLine(p);
               Console.WriteLine("Failed to login ");
                
             }
           }
       }

       public void LoadUsers()
       {

           string Data;

           StreamReader sr = new StreamReader(@"Expressions\combo.txt");
           while ((Data = sr.ReadLine()) != null)
           {
               ComboList.Add(Data);
           }
       }
       private bool IsElementPresent(By by)
       {
           try
           {
               Driver.Instance.FindElement(By.XPath("//span[@translate='TITLE_LOGOUT']"));
              
               return true;

           }
           catch (NoSuchElementException)
           {
               return false;

           }

       }
   }
}


most username/password combos you find on the internet are in the USERNAME:PASSWORD format anyways
(Jan 17, 2018 02:21 PM)Onii Wrote:  you don't have to have a user list and a password list. just have a single combo file and separate username and password with a special character, in most cases that is : and then have one foreach and split the line into username and password

Code
namespace Example
{
  [TestClass]
  public class AuthenticationTests
  {
      List<string> ComboList = new List<string>();

      [TestInitialize]
      public void Init()
      {
          Driver.Initialize();
      }

      [TestMethod]
     
      public void UserLogin()
      {
          LoadUsers();
          TryToLogin();
      }

 
      public void TryToLogin()
      {
   
          LoginPage.GoTo();
     
          foreach (string data in ComboList)
          {
            string[] user = data.Split(':');
            LoginPage.LoginAs(user[0]).WithPassword(user[1]).Login();
            if (IsElementPresent(By.XPath("//span[@translate='TITLE_LOGOUT']")))
            {
              Console.WriteLine("Logged in successfully");
              Driver.Instance.Close();
              Driver.Instance.Quit();
            }
            else
            {
              Console.WriteLine(p);
              Console.WriteLine("Failed to login ");
               
            }
          }
      }

      public void LoadUsers()
      {

          string Data;

          StreamReader sr = new StreamReader(@"Expressions\combo.txt");
          while ((Data = sr.ReadLine()) != null)
          {
              ComboList.Add(Data);
          }
      }
      private bool IsElementPresent(By by)
      {
          try
          {
              Driver.Instance.FindElement(By.XPath("//span[@translate='TITLE_LOGOUT']"));
             
              return true;

          }
          catch (NoSuchElementException)
          {
              return false;

          }

      }
  }
}


most username/password combos you find on the internet are in the USERNAME:PASSWORD format anyways

You don't see how this:
Code
foreach (string u in UserList)
    foreach (string p in PasswordList)
...
Is different than what you're doing? ❓

Take a look again... "For every user, test every password"

It's not matching a username to a single password.
Getting Started: C/C++
[C/C++/.NET/x86 ASM - Automation Programmer]


Possibly Related Threads...
Thread / Author Replies Views Last Post
[C#] by 991z3r0Aug 13, 2019 11:35 AM 2 122 Aug 13, 2019 11:35 AM
Last Post: 991z3r0
[.NET] by MalwareMopAug 7, 2019 02:18 PM 0 141 Aug 7, 2019 02:18 PM
Last Post: MalwareMop
[C#] by TunabishJun 16, 2018 12:00 PM 9 302 Jun 16, 2018 12:00 PM
Last Post: 0xDEAD10CC