Click here to Skip to main content
14,545,215 members
Rate this:
Please Sign up or sign in to vote.
Hello guys, I made a PHP API I am testing it with the postman when log in API sends you cookie contains token (JWT) then you can perform other actions everything is working fine on postman and I can see the cookie, but when i made the client-side when I log in the cookie does not exist I don't know why?

What I have tried:

<?php
/////////////////////////
// Authentication code.
/////////////////////////

// headers
header('Access-Control-Allow-Origin: domain');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

// include bootstraper
require_once "../../index.php";

// instantiate admin model
$admin_model = new Admin();
$admin_data = $admin_model->read_admin()[0];

// get request raw data from client (user)
$raw_data = json_decode(file_get_contents("php://input"), true);

// success can login
if ($raw_data["username"] == $admin_data["username"]
    && $raw_data["password"] == $admin_data["password"]) {

    // create token
    $new_token = JWT::sign([
        "algo" => "sha256",
        "typ" => "jwt",
    ], [
        "admin" => true,
        "iat" => date("Y-m-d H:i:s"),
        "exp" => date("Y-m-d H:i:s", strtotime("+1 minutes", strtotime(date("Y-m-d H:i:s")))),
    ], SECRET);

    // if token not exists or empty generate new token and send success respons
    if (!isset($_COOKIE["token"])) {
        setcookie("token", $new_token, time() + 60, "/");
        echo json_encode(["message" => "New token generated!", "data" => [], "logged" => true]);
        exit();
    }

    // verify the token if it's invalide generate new token and send success respons
    if (!JWT::verify($_COOKIE["token"], SECRET)) {
        setcookie("token", $new_token, time() + 60, "/");
        echo json_encode(["message" => "New token generated!", "data" => [], "logged" => true]);
        exit();
    }

    // send success respons
    echo json_encode(["message" => "Success!", "data" => [], "logged" => true]);

} else { // invalide inputs

    // send error respons
    echo json_encode(["message" => "Error!", "data" => [], "logged" => false]);

}
Posted
Updated 23-May-20 9:19am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100