我已经使用JWT api命名空间创建了一个端点,但是似乎无法使身份验证部分正常工作,我使用了wp-json / jwt-auth / v1 / token来访问令牌,但是该怎么办呢?验证自定义端点?
下面是一些代码,我曾尝试在邮递员中进行测试,但遇到403至的错误,找不到与URL和请求方法匹配的路由
function 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;
}
) );
答案 0 :(得分:-1)
Json Web令牌需要“秘密密钥”来验证API调用。您既可以在后端生成它,然后将其传递给前端以用于随后的其他api调用,也可以将其静态存储在前端的环境变量中(为安全起见)。 (可选)如果您有用户登录,则也可以将令牌附加到用户对象。
最后,您可以在任何受保护的路由中验证该令牌。
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');
}
})