WordPress中JWT验证调用错误类致403算法不允许问题
解决JWT Authentication for WP REST API与The Events Calendar的类冲突问题
问题概况
在多插件共存的WordPress项目中,使用JWT Authentication for WP REST API插件实现REST API认证时,出现以下问题:
- 调用
/jwt-auth/v1/token端点可正常获取令牌 - 调用
/jwt-auth/v1/token/validate端点验证令牌时,返回403状态码及"Algorithm not allowed"错误 - 排查确认:验证逻辑加载了The Events Calendar插件的
Firebase\JWT\JWT类,而非JWT认证插件自带的对应类
相关请求与响应示例
登录请求
curl --request POST \ --url http://localhost:12345/wp-json/jwt-auth/v1/token \ --header 'Accept: application/json' \ --header 'Content-Type: application/json' \ --data '{ "username": "hello@example.com", "password": "password" }'
验证请求
curl --request POST \ --url http://localhost:12345/wp-json/jwt-auth/v1/token/validate \ --header 'Authorization: Bearer {{ token }}'
错误响应
{ "code": "jwt_auth_invalid_token", "message": "Algorithm not allowed", "data": { "status": 403 } }
类路径对比
- 当前错误加载的类路径:
/var/www/hello-world/public_html/wp-content/plugins/the-events-calendar/common/vendor/firebase/php-jwt/src/JWT.php - 期望加载的类路径:
/var/www/hello-world/public_html/wp-content/plugins/jwt-authentication-for-wp-rest-api/includes/vendor/firebase/php-jwt/src/JWT.php
解决方案
方案一:调整插件加载顺序
WordPress默认按插件目录名的字母顺序加载插件,修改JWT认证插件的目录名,让它排在The Events Calendar之前:
- 将
jwt-authentication-for-wp-rest-api重命名为00-jwt-authentication-for-wp-rest-api(前缀加数字确保优先加载) - 刷新WordPress后台插件列表,重新激活插件
方案二:修改JWT认证插件的类加载逻辑
在JWT认证插件的主文件(如jwt-authentication-for-wp-rest-api.php)开头,手动引入自身的JWT类并确保优先注册:
// 引入插件自带的JWT相关类 require_once plugin_dir_path(__FILE__) . 'includes/vendor/firebase/php-jwt/src/JWT.php'; require_once plugin_dir_path(__FILE__) . 'includes/vendor/firebase/php-jwt/src/Key.php'; // 确保类未被其他插件覆盖 if (!class_exists('Firebase\JWT\JWT', false)) { class_alias('Firebase\JWT\JWT', 'Firebase\JWT\JWT'); }
⚠️ 注意:修改插件核心文件会在插件更新时被覆盖,建议备份自定义版本或改用MU-Plugin方案。
方案三:使用MU-Plugin强制优先加载JWT类
创建必须使用的插件(MU-Plugin),确保在所有普通插件之前加载JWT认证插件的类:
- 在
wp-content/目录下新建mu-plugins文件夹(若不存在) - 在该文件夹内创建
force-jwt-class-load.php文件,内容如下:
<?php /** * 强制优先加载JWT Authentication插件的Firebase JWT类 */ add_action('plugins_loaded', function() { $jwt_class_path = WP_CONTENT_DIR . '/plugins/jwt-authentication-for-wp-rest-api/includes/vendor/firebase/php-jwt/src/'; // 优先引入目标类文件 require_once $jwt_class_path . 'JWT.php'; require_once $jwt_class_path . 'Key.php'; }, 1); // 设为1确保在所有插件加载前执行
内容的提问来源于stack exchange,提问作者kellymandem
相关产品推荐
相关产品推荐

