CORS 发布 Ionic 4、WordPress 5.2 和 JWT 身份验证

CORS Issue Ionic 4, WordPress 5.2 and JWT Authentication

我正在使用 Angular 6 和 Ionic 4 以及 Wordpress 5.2 和 JWT 身份验证来访问 wp-json 中的 API。我确定根据 JWT 身份验证启用 CORS,并在主题函数中自定义 CORS headers,但我仍然收到错误

Access to XMLHttpRequest at 'https://oc.xxxx.com/wp-json/erp/v1/crm/contacts' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

我的主题函数中的自定义CORS header如下,

function my_customize_rest_cors() {
  remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  add_filter( 'rest_pre_serve_request', function( $value ) {
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: GET' );
    header( 'Access-Control-Allow-Credentials: true' );
    header( 'Access-Control-Expose-Headers: Link', false );
    return $value;
  } );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );

在我的 Ionic 应用程序上,调用 API 内容的代码如下,

getContact() {
    var service = this;
    let url = service.appConfig.Shop_URL + "/wp-json/erp/v1/crm/contacts";
    url = this.initUrl(url, '');
    var headers = new Headers();
    headers.append('Authorization', 'Bearer ' + service.userService.token);
    headers.append('Access-Control-Allow-Origin', '*');
    return new Promise(function (resolve, reject) {
      service.http.get(url, { headers: headers }).pipe(map(res => res.json())).subscribe(data => {
        if (data) {
          service.cachedData = data;
          resolve(service.cachedData);
        }
        else {
          reject();
        }
      });
    });
  }

我错过了什么导致 CORS 阻塞?提前致谢。

要使身份验证服务正常工作,您需要安装 wp-api-jwt-auth 插件,它允许您生成身份验证令牌。

仔细遵循 plugin information page 上提供的所有安装和设置说明。

一般来说,您需要做以下事情:

1 - 安装 JWT Authentication for WP REST API 插件。

2 - 编辑 .htaccess 文件以启用 HTTP 授权 Header。 (大多数共享主机默认禁用此功能。)

为 JWT 插件编辑 .htaccess 文件后,我的现在看起来像这样:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=

3 - 添加一个 密钥 并启用 CORS 支持 添加两个常量(JWT_AUTH_SECRET_KEYJWT_AUTH_CORS_ENABLE) 到 wp-config.php 文件。

/**
 * WordPress JWT Authentication for WP REST API
 *
 * You can generate secret keys using the WordPress.org secret-key service at:
 * https://api.wordpress.org/secret-key/1.1/salt/
 */
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);

4 - 最后,激活 wp-admin 中的插件。

function my_customize_rest_cors() {
  remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
  add_filter( 'rest_pre_serve_request', function( $value ) {
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT' );
    header( 'Access-Control-Allow-Credentials: true' );
    header( 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization' );
    header( 'Access-Control-Expose-Headers: Link', false );
    return $value;
  } );
}
add_action( 'rest_api_init', 'my_customize_rest_cors', 15 );

function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT' );
    header( 'Access-Control-Allow-Credentials: true' );
    header( 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization' );
    header( 'Access-Control-Expose-Headers: Link', false );
}
add_action('init','add_cors_http_header');

使用任一函数进行检查