Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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
<?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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900