Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用wp-rest的jwt身份验证创建需要身份验证的api端点_Php_Wordpress_Api - Fatal编程技术网

Php 如何使用wp-rest的jwt身份验证创建需要身份验证的api端点

Php 如何使用wp-rest的jwt身份验证创建需要身份验证的api端点,php,wordpress,api,Php,Wordpress,Api,我已经使用JWTAPI名称空间创建了一个端点,但似乎无法使身份验证部分正常工作,我已经使用了wp json/JWT auth/v1/token来访问令牌,但是如何对自定义端点进行身份验证 下面是一些代码,我曾尝试在postman中进行测试,但从403到找不到匹配URL和请求方法的路由,出现了几个错误 功能wp\U寄存器\U crm\U路由{ // register_rest_route() handles more arguments but we are going to stick to t

我已经使用JWTAPI名称空间创建了一个端点,但似乎无法使身份验证部分正常工作,我已经使用了wp json/JWT auth/v1/token来访问令牌,但是如何对自定义端点进行身份验证

下面是一些代码,我曾尝试在postman中进行测试,但从403到找不到匹配URL和请求方法的路由,出现了几个错误

功能wp\U寄存器\U crm\U路由{

// register_rest_route() handles more arguments but we are going to stick to the basics for now.
register_rest_route( '/wp-json/jwt-auth/v1', 'addproduct', array(
    // By using this constant we ensure that when the WP_REST_Server changes our readable endpoints will work as intended.
    'methods'  =>'POST',
    // Here we register our callback. The callback is fired when this endpoint is matched by the WP_REST_Server class.
    'callback' => 'addProductFromCRM',
    'permission_callback' => function ($request) {
        if (current_user_can('edit_others_posts'))
        return true;
 }
) );

Json web令牌需要“密钥”来验证API调用。您可以在后端生成该令牌,并将其传递给前端,以便在以后的每一次API调用中使用,也可以将其静态存储在前端的环境变量中以确保安全。如果有用户登录,则可以将该令牌附加到用户对象l

最后,您可以在任何受保护的路由中验证该令牌

Javascript实现
他为PHP添加了标签,因此在后端而不是前端保存密钥更安全。这只是一个示例来演示。因为他没有指定正在使用的PHP包,所以我只给出了一个JS实现来获取解决方案的摘要。
jwt.sign({user}, 'privatekey', { expiresIn: '1h' },(err, token) => {
            if(err) { console.log(err) }    
            res.send(token);
        });


jwt.verify(req.token, 'privatekey', (err, authorizedData) => {
        if(err){
            //If error send Forbidden (403)
            console.log('ERROR: Could not connect to the protected route');
            res.sendStatus(403);
        } else {
            //If token is successfully verified, we can send the autorized data 
            res.json({
                message: 'Successful log in',
                authorizedData
            });
            console.log('SUCCESS: Connected to protected route');
        }
    })