User Authentication using REST API and JSON Web Tokens (JWT) – Step 7

User Authentication using REST API and JSON Web Tokens (JWT) – Step 7

Login user with JSON Web Token

Almost all the process is similar as we done in previous step for login user but now we do the same thing with JWT. For this we have to perform the following steps:

  1. Now create Login Function in user. php of object folder
    //Login Student
    public function readLogin($email, $password)
    {
        $query = "Select * from " . $this->tableName . " where email='" . $email . "' LIMIT 1";
        try {
            $stmt = $this->conn->prepare($query);
            $stmt->execute();
            return $stmt;
        } catch (PDOException $e) {
            echo json_encode(array("AuthenticationStudentSQLError" => $e->getMessage()));die;
        }

    }

2. Use theses line in the starting of login.php files

require ‘../vendor/autoload.php’;

use Firebase\JWT\JWT;

include_once ‘../config/core.php’;

3.Now change in login. Php file in user folder

if (
    !empty($data->email) &&
    !empty($data->password)
) {
    $stmt = $user->readLogin($data->email, $data->password);
    $rowcount = $stmt->rowCount();

    if ($rowcount > 0) {
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            extract($row);
            if (password_verify($data->password, $password)) {

                array_push($payload, array('data' => array("email" => $user->email)));
                $jwt = JWT::encode($payload, $key);
                http_response_code(200);
                echo json_encode(array("message" => "Login Successfully.", "token" => $jwt));
            } else {
                http_response_code(401);
                echo json_encode(array("message" => "Username/Password Incorrect."));

            }
        }
    } else {
        http_response_code(401);
        echo json_encode(array("message" => "Username/Password Incorrect."));

    }
} else {
    http_response_code(400);
    echo json_encode(array("message" => "Unable to Find Student. Data is incomplete."));
}

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*