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

跨域AJAX是否可携带Cookie?附WordPress用户身份同步场景

Alright, let's break down your problem step by step. First, your hunch about cookies not being sent in cross-domain AJAX requests is almost certainly right—here's how to fix that, plus some alternative approaches if that doesn't pan out or if you want a more robust production-grade solution.

Cross-domain AJAX requests don't send cookies by default for security reasons. To make this work, you need to configure both your App's frontend and your WordPress backend:

Frontend (jQuery AJAX)

Update your $.ajax call to include the withCredentials: true option. This tells the browser to send cookies associated with the WordPress domain along with the request:

$.ajax({
  url: 'https://your-wordpress-domain.com/custom-session-page/',
  type: 'GET',
  xhrFields: {
    withCredentials: true
  },
  success: function(response) {
    // Store the session ID in a cookie or local storage
    document.cookie = `wp_session_id=${response.sessionId}; path=/; domain=your-app-domain.com`;
  },
  error: function(xhr) {
    console.error('Request failed:', xhr);
  }
});

Note: You can also add crossDomain: true, but withCredentials is the critical setting here to trigger cookie transmission.

Backend (WordPress)

Your WordPress custom page needs to send the correct CORS headers to allow credentials from your App's domain. Do NOT use Access-Control-Allow-Origin: *—that conflicts with credentialed requests. Instead, specify your App's exact domain:

Add this at the top of your custom page template (or hook into the init action if you prefer a cleaner approach):

// Allow requests from your App's domain
header("Access-Control-Allow-Origin: https://your-app-domain.com");
// Explicitly allow credentials (cookies)
header("Access-Control-Allow-Credentials: true");
// Handle preflight OPTIONS requests (required for complex cross-domain requests)
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type");
    exit;
}

// Rest of your logic to fetch user ID and generate session ID
$user_id = get_current_user_id();
// Add your session ID generation code here
echo json_encode(['sessionId' => $your_generated_session_id]);
exit;

Verify the Fix

Check your browser's DevTools > Network tab:

  • Look for the Cookie header in the request to your WordPress page—it should include the WordPress session cookie (usually wordpress_logged_in_...).
  • Ensure the response headers include Access-Control-Allow-Origin set to your App's domain and Access-Control-Allow-Credentials: true.

Alternative Solutions If Cookies Aren't Working or You Want a Better Approach

If for some reason the cookie method still fails (e.g., strict browser privacy settings like SameSite cookies), or if you want a more secure/scalable solution, consider these options:

1. Use OAuth2/OpenID Connect

This is the industry standard for cross-domain user authentication. Set up an OAuth2 server on WordPress using plugins like OAuth2 Server or WP OAuth Server:

  • Users log in directly on your WordPress site (no cross-domain cookie issues).
  • Your App redirects users to WordPress for authorization.
  • WordPress returns an access token to your App.
  • Your App uses this token to fetch the user ID and other data from a WordPress REST API endpoint.

2. Server-Side Proxy

Instead of having your App frontend call WordPress directly, have your App's backend act as a middleman:

  • Your App frontend sends a request to your own server.
  • Your server makes a server-to-server request to WordPress (this avoids cross-domain issues entirely, since server requests don't follow browser CORS rules).
  • Your server fetches the session ID/user ID and returns it to your frontend.

3. JWT (JSON Web Tokens)

Replace session IDs with JWTs. WordPress can generate a signed JWT containing the user ID, which your App can store and use for subsequent requests:

  • Use a WordPress plugin like JWT Authentication for WP REST API to enable JWT endpoints.
  • After user login on WordPress, generate a JWT and send it to your App.
  • Your App stores the JWT (in localStorage or a cookie) and sends it in the Authorization: Bearer <token> header for future requests to WordPress.

4. Shared Top-Level Domain (If Applicable)

If your WordPress and App domains share a top-level domain (e.g., wp.yourdomain.com and app.yourdomain.com), configure WordPress to set cookies with a domain of .yourdomain.com. This allows the cookie to be shared across subdomains, eliminating cross-domain issues entirely.

内容的提问来源于stack exchange,提问作者cebo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:11:14