如何自定义WooCommerce与WordPress API的JWT认证及无头Next.js权限管控
无头WooCommerce + Next.js 搭建及自定义JWT接口权限配置
一、基础项目搭建
1. WordPress与WooCommerce准备
确保WordPress站点已安装并激活WooCommerce插件,REST API默认开启。在WooCommerce后台生成API密钥(WooCommerce > 设置 > 高级 > REST API),保存好Consumer key和Consumer secret。
2. Next.js项目初始化
创建项目并安装依赖:
npx create-next-app@latest wc-nextjs-demo cd wc-nextjs-demo npm install @woocommerce/woocommerce-rest-api
3. 配置WooCommerce API连接
在项目中创建lib/woocommerce.js文件:
import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api"; const api = new WooCommerceRestApi({ url: "https://your-wordpress-site.com", // 替换为你的WP站点地址 consumerKey: "your-consumer-key", consumerSecret: "your-consumer-secret", version: "wc/v3", }); export default api;
4. 基础数据请求示例
在pages/index.js中展示产品列表:
import api from "../lib/woocommerce"; export async function getStaticProps() { const { data: products } = await api.get("products"); return { props: { products } }; } export default function Home({ products }) { return ( <div> <h1>产品列表</h1> <ul> {products.map((product) => ( <li key={product.id}>{product.name}</li> ))} </ul> </div> ); }
二、自定义JWT认证限制接口方法
1. WordPress端配置JWT插件
安装并激活JWT Authentication for WP REST API插件,修改wp-config.php添加配置:
// 生成随机密钥可访问:https://api.wordpress.org/secret-key/1.1/salt/ define('JWT_AUTH_SECRET_KEY', 'your-random-secret-key'); // 开启CORS支持 define('JWT_AUTH_CORS_ENABLE', true);
2. 自定义权限控制逻辑
在主题的functions.php或自定义插件中添加以下代码:
function wc_rest_restrict_modification_methods($result, $wp_rest_server, $request) { // 定义需要限制的端点及方法 $protected_routes = [ '/wc/v3/products' => ['POST', 'PUT', 'DELETE'], '/wc/v3/orders' => ['POST', 'PUT', 'DELETE'] ]; $current_route = $request->get_route(); $current_method = $request->get_method(); // 匹配受保护的路由与方法 foreach ($protected_routes as $route => $methods) { if (strpos($current_route, $route) !== false && in_array($current_method, $methods)) { // 检查JWT令牌是否存在且有效 $auth_header = $request->get_header('Authorization'); if (!$auth_header || strpos($auth_header, 'Bearer ') === false) { return new WP_Error('rest_unauthorized', '需要JWT认证', ['status' => 401]); } $token = trim(str_replace('Bearer ', '', $auth_header)); $validation = JWT_Auth::validate_token($token); if (is_wp_error($validation)) { return $validation; } } } return $result; } add_filter('rest_request_before_callbacks', 'wc_rest_restrict_modification_methods', 10, 3);
3. Next.js端JWT使用示例
获取JWT令牌
async function fetchJwtToken(username, password) { const response = await fetch('https://your-wordpress-site.com/wp-json/jwt-auth/v1/token', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password }), }); const data = await response.json(); return data.token; }
调用受保护的接口(如创建产品)
import api from "../lib/woocommerce"; async function createNewProduct(token, productData) { try { const response = await api.post("products", productData, { headers: { Authorization: `Bearer ${token}`, }, }); return response.data; } catch (error) { console.error('创建产品失败:', error.response.data); throw error; } }
4. 关键注意事项
- WooCommerce API密钥仍需配置:JWT是额外的权限验证,WooCommerce自身的API密钥用于基础API访问权限验证,二者缺一不可。
- 测试验证:用调试工具测试:
- GET
/wp-json/wc/v3/products:无需令牌,正常返回数据 - POST
/wp-json/wc/v3/products:不带Bearer令牌返回401错误,携带有效令牌则正常执行
- GET
- 令牌过期处理:JWT令牌默认有过期时间,需在前端调用
/wp-json/jwt-auth/v1/token/refresh接口处理刷新逻辑
内容的提问来源于stack exchange,提问作者sianami
相关产品推荐
相关产品推荐

