如何从PHP后端向前端Web应用程序发送HttpOnly Cookie JWT令牌?

时间:2020-05-31 01:56:15

标签: php reactjs axios httponly

我知道如何从PHP脚本使用echo向REACTJS脚本发送jwt令牌,该脚本获得Axios的响应,但是如果我想使用包含该JWT令牌的Http Only cookie的安全方式,该怎么办?它给用户,以便用户可以登录?请问您能为我写一个代码示例,因为我搜索了几天,但网络上没有足够的资源。调用setcookie()函数会做所有事情还是我需要回显某些内容,以便用户知道他已登录?

没有Http Only cookie,这就是我在用户登录后发送JWT的方式:

前端:

if (canSubmit) {
                axios
                    .post(
                        'http://localhost/React_ToDo_APP/to-do/src/PHPFiles/UserSignIn.php',
                        JSON.stringify(this.state.signInUserInfo)
                    )
                    .then((response) => {
                        const userSessionDataTmp = { userName: response.data.userName, userJWT: response.data.jwt };
                        this.setState({ signedInUserSessionData: userSessionDataTmp }, () => {
                            this.setState({ isUserSignedIn: true });
                        });
                        console.log(response.data.jwt);
                    })
                    .catch((error) => {
                        console.log(
                            'error: ',
                            error.response,
                            'Message: ',
                            error.response.data.message,
                            'Password: ',
                            error.response.data.password
                        );
                        let signInErrorsTmp = { ...this.state.signInErrors };
                        signInErrorsTmp.userNotFoundError = 'You entred a wrong Email or Password !';
                        this.setState({ signInErrors: signInErrorsTmp }, () => {
                            console.log(this.state.signInErrors.userNotFoundError);
                        });
                    });
            }

后端:

 $secret_key = "YOUR_SECRET_KEY";
            $issuer_claim = "THE_ISSUER";//this can be the servername
            $audience_claim = "THE_AUDIENCE";
            $issuedat_claim = time();
            $notbefore_claim = $issuedat_claim +10;//not before in seconds
            $expire_claim = $issuedat_claim +300;//expire time in seconds
            //echo (date('H:i', $expire_claim)) ;
            $token = array(
                "iss" => $issuer_claim,
                "aud" => $audience_claim,
                "iat" => $issuedat_claim,
                "nbf" => $notbefore_claim,
                "exp" => $expire_claim,
                "data" => array(
                    "id" => $id
                )
                );
        http_response_code(200);       
        $jwt = JWT::encode($token,$secret_key);
        echo json_encode(
        array(
            "message" => "Successful login. ",
            "jwt" => $jwt,
            "expireAt" => $expire_claim,
            "userName" => $username
        )

0 个答案:

没有答案