You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在WordPress REST API中使用HTTP-only Cookie:识别Cookie归属

问题解决及原理说明

一、服务器如何确定Cookie归属?

服务器通过以下逻辑识别Cookie归属:

  • 服务器下发Cookie时,会通过Set-Cookie响应头附带域名、路径、安全属性、HttpOnly等规则,定义Cookie的生效范围。
  • 客户端浏览器会存储符合规则的Cookie,后续向匹配域名、路径的服务器发送请求时,会自动将Cookie通过请求头的Cookie字段携带给服务器。
  • 服务器解析Cookie请求头,根据Cookie的名称和值关联到对应用户会话,以此确定归属。

二、客户端需要传递哪些数据?

核心是让请求自动携带已存储的Cookie,对于fetch请求必须显式设置credentials参数:

  • 同域场景:设置credentials: 'same-origin'
  • 跨域场景:设置credentials: 'include'

fetch默认不会携带Cookie,不配置该参数会导致服务器无法获取客户端已存储的Cookie。

三、你的代码问题修复

1. JavaScript代码修改

补充async关键字、请求方法/体,以及关键的credentials配置:

async function setCookie() {
    const res = await fetch('/login', {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ username, password })
    });
    
    console.log(await res.json()); // Success
}

async function checkCookie() {
    const res = await fetch('/check-cookie', {
        credentials: 'same-origin'
    });
    
    console.log(await res.json()); // 现在应返回true
}

2. PHP代码优化说明

  • 你设置的setCookie中secure: true意味着仅HTTPS环境下Cookie才会被客户端存储,如果是本地HTTP测试,需暂时将其改为false,上线后再恢复。
  • WordPress环境建议使用内置的wp_set_auth_cookie函数设置认证Cookie,兼容WordPress会话逻辑:
<?php

// Hooked to /login endpoint
function login($request) {
    $credentials = $request->get_json_params();
    $user = wp_authenticate($credentials['username'], $credentials['password']);
    
    if (is_wp_error($user)) {
        return 'Failed';
    }
    
    wp_set_auth_cookie($user->ID, true, is_ssl());
    return 'Success';
}

// Hooked to /check-cookie endpoint
function checkCookie() {
    return is_user_logged_in() ? true : isset($_COOKIE['cookie-name']);
}

四、额外注意事项

  • 确保Cookie的Path设置正确(你设为/,全站生效,无问题)。
  • HttpOnly: true是安全设置,禁止JS读取Cookie,但不影响请求自动携带,建议保留。

内容的提问来源于stack exchange,提问作者E-g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 21:32:53