首页 > 解决方案 > 如何从 WordPress 解析 Node Express 会话

问题描述

有 :

Node.js 放入connect.sidcookie

res.isAuthenticated当用户从 Node.js 调用任何方法时,我可以验证用户身份验证

但是如何通过 WordPress 验证用户身份?

WordPress 将页面呈现为 MVC 客户端

Node.js 用作 REST API

我有几个想法:

User: I want to example.domain 

Node: Yes, you're authorized and can get WP pages with true-auth flag

User: I want to logout from example.domain

Node: Yes, you're not authorized and can get WP pages with false-auth flag```

标签: javascriptphpnode.jswordpress

解决方案


如果 WP 和 Node.js 放在一个域中,那么 Cookies 包含在一个位置

您可以通过 WP 的 $_COOKIE["COOKIE NAME HERE"] 获取 Cookie

来自 Node.js 的 Passport.js 包含 session_id 作为名称为 connect_sid 的 cookie

当您从 WP 调用任何页面时,您可以在 cookie 中接收 connect_sid 并通过会话替换在 Node.js 端对其进行验证

节点(创建一个路由作为get):

router.get("/check", function (req, res) {
  res.send(req.isAuthenticated)
})

工作人员:

function get_auth_state(){
    $cookie = 'Cookie: connect.sid=' . urlencode($_COOKIE["connect_sid"]) . ';';

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "http://localhost-node-address/check",
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            $cookie
        ),
    ));

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        return "cURL Error #:" . $err;
    } else {
        return $response;
    }
}

推荐阅读