我有一个存储在 $_SESSION 变量中的第三方 api 的会话令牌,并希望能够在 WP Rest 请求中访问它。我可以使用 WP Rest 的内置 Nonce 身份验证 来做到这一点吗?
首先,我创建一个
wp_rest
nonce 和 l10n
用于脚本:
$params = array(
'nonce' => wp_create_nonce( 'wp_rest' )
);
wp_localize_script( 'my_script', 'user_tools', $params );
这是要求:
on('submit', '#mzStudioRegisterForm', function (event) {
event.preventDefault();
let form = event.target;
let data = new FormData(form);
data.append('_wpnonce', user_tools.nonce);
fetch(base_url + `registeruser?`, {method: 'POST', body: data, credentials: 'include'})
.then(r => r.json())
.then(json => console.log({"json": json}));
});
休息路线和回调是最小的:
function register_user_with_studio() {
// An example with 0 parameters.
register_rest_route(
'myplugin-auth/v1',
'/registeruser',
array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => __NAMESPACE__ . '\register_user',
'permission_callback' => '__return_true'
)
);
}
回调:
function add_user_to_studio( $request ) {
$params = $request->get_body_params();
// This is where I want to get the token from $_SESSION
return array( 'result' => 'Salaam. I can hear you.' );
}
WP nonce认证是否只对登录WP的用户有效?
在开发工具中,请求本身似乎确实在发送 cookie:
:authority: example.test
:method: POST
:path: /wp-json/myplugin-auth/v1/registeruser?
:scheme: https
accept: */*
(abridged)
content-type: multipart/form-data; boundary=----WebKitFormBoundaryoiTG77MAuyEduz00
cookie: PHPSESSID=8f4b03d3eaa814644ef29f7fea711a83
dnt: 1
origin: https://example.test
pragma: no-cache
sec-ch-ua: "Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
在后端匹配:
session_id();
// 8f4b03d3eaa814644ef29f7fea711a83