【问题标题】:How do I create an api endpoint that needs authentication using jwt authentication for wp rest如何使用 jwt 身份验证为 wp rest 创建需要身份验证的 api 端点
【发布时间】:2019-05-24 03:29:22
【问题描述】:

我已经使用 JWT api 命名空间创建了一个端点,但似乎无法让身份验证部分正常工作,我已经使用 wp-json/jwt-auth/v1/token 来获得对令牌的访问权限,但是我该怎么做验证自定义端点?

下面是一些代码,我已经尝试在邮递员中进行测试,但是从 403 到找不到与 URL 和请求方法匹配的路由

函数 wp_register_crm_routes() {

// 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;
 }
) );

【问题讨论】:

    标签: php wordpress api


    【解决方案1】:

    Json Web 令牌需要“密钥”来验证 API 调用。您可以在后端生成它并将其传递给前端以供所有其他后续 api 调用使用,也可以将其静态存储在前端的环境变量中(为了安全起见)。 (可选)如果您有用户登录,那么您也可以将令牌附加到用户对象。

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

    Javascript 实现

    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');
            }
        })
    

    【讨论】:

    • 他给PHP加了标签,把秘钥放在后端比前端更安全。
    • 这只是一个示例。由于他没有指定使用的PHP包,所以我只是给出了一个JS实现来获取解决方案的摘要。
    猜你喜欢
    • 2016-03-24
    • 2016-04-24
    • 1970-01-01
    • 2019-01-01
    • 2016-10-06
    • 2018-06-20
    • 2015-05-14
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多