3

I am trying to verify username, password, and software token number of a C# Windows Form to values in MySQL database.

My C# Code:

 private void btnlogin_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(txtusername.Text))
        {
            MessageBox.Show("Please insert username");
        }

        if (String.IsNullOrEmpty(txtpassword.Text))
        {
            MessageBox.Show("Please insert password");
        }

        var username = txtusername.Text;
        var password = txtpassword.Text;
        string Token = "28956";
        var SoftwareToken = token;
        WebRequest request = WebRequest.Create("https://mydomain.com.au/Verification.php?username=username&password=password&Token=SoftwareToken");
        request.Method = "GET";
        WebResponse response = request.GetResponse();
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        var responseFromServer = reader.ReadToEnd();
        responseFromServer.ToArray();
        /*I have tried:
        responseFromServer.ToArray();(because result on php page is an array.
  I have tried responseFromServer.ToString();*/
        MessageBox.Show(responseFromServer);
    }

My PHP code (Web service):

<?php
// Database Structure 
require_once('connect.php');

//Get password from the database for the user
$stmtus = $conn->prepare("SELECT password from `Users` where `email` = :Username");
$stmtus->bindParam(':Username', $username);
$username= $_GET['username'];;
$stmtus -> execute();
$password = $stmtus->fetch();

$un = $_GET['username'];
$pw = $_GET['password'];
$ust = $_GET['Token'];

if(password_verify($pw, $password[0])){
    $stmt = $conn->prepare("SELECT 
    COUNT(Token) AS cnt FROM `SoftwareToken` 
    LEFT JOIN User ON iduser = SoftwareToken.Consultant 
    WHERE Token = '$ust' 
    AND username = '$un'");
    $stmt->bindValue(':Username', $un);
    $stmt->bindValue(':Token', $ust);
    $stmt->execute();
    $result= array();
    while($SToken= $stmt->fetch(PDO::FETCH_OBJ)){
    array_push($result, $SToken->cnt);  
    }
echo json_encode($result);

}

$conn = null;

?>

I am battling to understand how I call the web service from the C# application, how do I pass the variables from the C# application to the web service and how do I return the json_encode to the C# application from the web service.

I am not a full-time programmer and this is my first encounter with web services. If there are any suggestions on how to improve either of the codes, I would much appreciate.

UPDATE

I have updated my code as assisted. When I run the php code with variables it runs and gives me a $result (array). A numeral answer 1.

When I test my code to display the result in a MessageBox, the MessageBox is empty. Why ?

  • [this](https://stackoverflow.com/questions/4015324/how-to-make-http-post-web-request) is more or less a duplicated question.. if you change the `$_GET` into `$_POST` in the PHP code you can use that answer. – Raymond Nijland Dec 05 '18 at 12:56
  • " If there is any suggestions on how to improve either of the codes," Well it looks like you are already using the correct php library for handling passwords, i wanted to write and also using prepared statements to prevent SQL injections.. Then i noticed this `WHERE Token = '$ust' AND username = '$un'");` in the SQL code which is still prone to SQL injections you should param it with `WHERE Token = :Token AND username = :Username);` – Raymond Nijland Dec 05 '18 at 13:01
  • @RaymondNijland Thanks for the advise. I think that I am passing the variables unsuccessfully from C# Windows Form Application to the PHP Web-Service. Please see my new question [here](https://stackoverflow.com/questions/53663736/how-to-pass-variables-from-c-sharp-windows-form-application-to-php-web-service). Maybe you have some advise? – CharlesWashington Dec 07 '18 at 05:47

2 Answers2

1

Of course you can call WebService from C#. There is a built in calss in System.

One Way:

WebRequest request = WebRequest.Create("http://localhost:8080/?username=john");
request.Method="GET";
WebResponse response = request.GetResponse();

Other Way:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8080/");
HttpResponseMessage response = await client.PostAsJsonAsync( "api/user", userName);
response.EnsureSuccessStatusCode();
György Gulyás
  • 1,290
  • 11
  • 37
  • Many thanks. I like the first method. To use the result in C# application, do I use `if(response = 1){ #dosomething }`? – CharlesWashington Dec 05 '18 at 14:31
  • Please mar the question to answered. Thx:) – György Gulyás Dec 05 '18 at 14:39
  • I did. How do I use the response in my c#? When I do `if(response = 1){ #dosomething }` I get error "Cannot convert type int to webresponse" – CharlesWashington Dec 05 '18 at 14:42
  • Please us the casting if( (int)response = 1) { #dosomething } – György Gulyás Dec 05 '18 at 14:44
  • `if( (int)response = 1) { #dosomething }` is not working. Same error: cannot implicitly convert type int to System.Net.WebResponse – CharlesWashington Dec 05 '18 at 16:35
  • Here is the sample, where you get the result: https://learn.microsoft.com/en-us/dotnet/framework/network-programming/how-to-request-data-using-the-webrequest-class. By the way The HttpClinet is better, in my opinion – György Gulyás Dec 05 '18 at 17:13
  • Thanks for the advise. I think that I am passing the variables unsuccessfully from C# Windows Form Application to the PHP Web-Service. Please see my new question [here](https://stackoverflow.com/questions/53663736/how-to-pass-variables-from-c-sharp-windows-form-application-to-php-web-service). Maybe you have some advise? – CharlesWashington Dec 07 '18 at 05:46
0

Code which I used:

    var username = txtusername.Text;
    var password = txtpassword.Text;
    string Token = "28956";
        var url = "https://mydomain.com.au/LoginVerification.php?";
        var var = "username=" + username + "&password=" + password + "&Token=" + Token ;
        var URL = url + var;
        //MessageBox.Show(URL);


        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.  
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.  
        var responseFromServer = reader.ReadToEnd();
        //MessageBox.Show(responseFromServer);
        // Display the content.  
        if (responseFromServer == "\n  Allow")
        {
            MessageBox.Show("Success");           
        }