User Authentication using REST API and JSON Web Tokens (JWT) – Step 6
Create user with JSON Web Token
Almost all the process is similar as we done in previous step to create the user but now we do the same thing with JWT. For this we have to perform the following steps:
- Download composer using command in api folder using composer require firebase/php-jwt
- Create new file core. php in config folder
<?php
// show error reporting
error_reporting(E_ALL);
// set your default time-zone
date_default_timezone_set('Asia/Kolkata');
// variables used for jwt
$key = "shairy";
$payload = array(
"issued_at" => time(),
"expiration_time" => time() + (365 * 24 * 60 * 60), // valid for 1 year
"issuer" => "http: //example.com",
);
3. Use thses lines in starting of create_user.php files
require ‘../vendor/autoload.php’;
use Firebase\JWT\JWT;
include_once ‘../config/core.php’;
4. The following create code change and use JWT
// create the user
if (
!empty($user->name) &&
!empty($user->email) &&
!empty($user->password) &&
$user->create()
) {
// set response code
http_response_code(200);
array_push($payload, array('data' => array("email" => $user->email)));
$jwt = JWT::encode($payload, $key);
// tell the user
echo json_encode(array("message" => "User was inserted.", "token" => $jwt));
}