WordPress JWT 教程2: 完成一个更新用户信息的接口

当然可以!下面是一个 安全、完整 的 WordPress REST API 接口示例,用于 让用户修改自己的信息(如昵称、邮箱等),并且在接口内部 通过 JWT 验证后自动获取当前用户的 ID,确保用户只能修改自己的资料。

✅ 前提:你已经按照上一回答配置好了 firebase/php-jwt 并能成功验证 Token。


✅ 目标

  • 路由:POST /wp-json/my-jwt/v1/update-profile
  • 方法:仅允许已认证用户调用
  • 功能:更新当前用户的 display_nameuser_email(可扩展)
  • 安全:用户只能修改自己的信息,不能冒充他人

✅ 接口代码(添加到你的自定义插件中)

// 在你的 my-jwt-auth.php 插件文件中追加以下代码

add_action('rest_api_init', function () {
    register_rest_route('my-jwt/v1', '/update-profile', [
        'methods' => 'POST',
        'callback' => 'my_jwt_update_profile_handler',
        'permission_callback' => 'my_jwt_validate_token', // 复用之前的验证函数
    ]);
});

/**
 * 更新当前用户资料
 */
function my_jwt_update_profile_handler(WP_REST_Request $request)
{
    // 从请求中获取 jwt_user_id(已在 my_jwt_validate_token 中设置)
    $user_id = $request->get_param('jwt_user_id');
    if (!$user_id) {
        return new WP_Error('no_user', 'User not authenticated.', ['status' => 401]);
    }

    $user = get_user_by('ID', $user_id);
    if (!$user) {
        return new WP_Error('invalid_user', 'User not found.', ['status' => 404]);
    }

    // 获取要更新的字段(只允许安全字段)
    $allowed_fields = ['display_name', 'first_name', 'last_name', 'user_email'];
    $updates = [];

    foreach ($allowed_fields as $field) {
        if ($request->has_param($field)) {
            $value = sanitize_text_field($request->get_param($field));
            if ($field === 'user_email') {
                $value = sanitize_email($value);
                if (!is_email($value)) {
                    return new WP_Error('invalid_email', 'Invalid email address.', ['status' => 400]);
                }
                // 检查邮箱是否已被他人使用
                if (email_exists($value) && $value !== $user->user_email) {
                    return new WP_Error('email_exists', 'This email is already in use.', ['status' => 400]);
                }
            }
            $updates[$field] = $value;
        }
    }

    if (empty($updates)) {
        return new WP_Error('no_data', 'No valid fields to update.', ['status' => 400]);
    }

    // 执行更新
    $updates['ID'] = $user_id;
    $result = wp_update_user($updates);

    if (is_wp_error($result)) {
        return $result;
    }

    // 返回更新后的用户信息
    $updated_user = get_user_by('ID', $user_id);
    return new WP_REST_Response([
        'success' => true,
        'message' => 'Profile updated successfully.',
        'user' => [
            'id' => $updated_user->ID,
            'username' => $updated_user->user_login,
            'display_name' => $updated_user->display_name,
            'first_name' => $updated_user->first_name,
            'last_name' => $updated_user->last_name,
            'email' => $updated_user->user_email,
        ],
    ], 200);
}

✅ 使用示例

请求地址:

POST /wp-json/my-jwt/v1/update-profile

Headers:

Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.xxxxx
Content-Type: application/json

Body(JSON):

{
  "display_name": "New Display Name",
  "first_name": "John",
  "last_name": "Doe",
  "user_email": "john.new@example.com"
}

🔒 只有传递了有效 JWT 且 token 中包含合法用户 ID 的请求才能成功。
即使攻击者知道别人 ID,也无法绕过 jwt_user_id(因为 token 是签名的,无法伪造)。


✅ 安全说明

安全点 说明
✅ 用户隔离 只能修改 jwt_user_id 对应的用户,无法指定其他 ID
✅ 字段白名单 仅允许更新预定义的安全字段,防止任意字段写入(如 user_pass、role)
✅ 邮箱验证 检查格式 + 是否被占用
✅ 数据清理 使用 sanitize_text_fieldsanitize_email
✅ 无密码修改 不处理密码(如需改密码,应单独做“修改密码”接口 + 旧密码验证)

🚫 不要做的事

  • 不要接受 user_idID 作为请求参数(否则可越权)
  • 不要允许更新 user_loginuser_passrole 等敏感字段(除非有额外验证)
收藏
评论
打赏
WordPress JWT 教程1: Wordpress 添加 JWT 验证
上一篇
没有了
下一篇

0 条评论

像素鱼丸
88495 阅读
142 发布
3 收藏
动态
Mirage 主题 v2.56.0 发布
MirageV 主题 v2.6.4 发布
BotV 插件 v1.7.0 发布
MirageV 主题 v2.6.0 发布
FishV 主题 v1.14 发布
MirageV-App 小程序 v1.2.2 发布
LandV 企业主题 v2.6.0 发布
FishV 主题 v1.21.0 发布
生成中...
真诚赞赏,手留余香
登录
注册
重置密码