CORS Issue Ionic 4, WordPress 5.2 and JWT Authentication

早过忘川 提交于 2021-01-29 04:03:22

问题


I am using Angular 6 and Ionic 4 with Wordpress 5.2 and JWT Authentication to access an API in wp-json. I was sure to enable CORS according to JWT Authentication and also custom CORS headers in Theme function but I am still receiving the error

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.

The custom CORS header in my theme function is as follows,

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 );

and on my Ionic app, the code to call the API content is as follows,

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();
        }
      });
    });
  }

What did I miss that cause the CORS blocking? Thanks in advance.


回答1:


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');

Use either one of the functions to check




回答2:


To make the authentication service work, you need to install the wp-api-jwt-auth plugin, which allows you to generate an authentication token.

Carefully follow all installation and setup instructions provided on the plugin information page.

In general, you need to do the following:

1 - Install the JWT Authentication for WP REST API plugin.

JWT Authentication for WP REST API

2 - Edit the .htaccess file to enable the HTTP Authorization Header. (Most of the shared hosting has this disabled by default.)

After editing the .htaccess file for the JWT plugin, mine now looks like this:

# 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=$1

3 - Add an secret key and enable the CORS Support adding two constants (JWT_AUTH_SECRET_KEY, JWT_AUTH_CORS_ENABLE) to the wp-config.php file.

/**
 * 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 - And finally, activate the plugin in wp-admin.



来源:https://stackoverflow.com/questions/57619415/cors-issue-ionic-4-wordpress-5-2-and-jwt-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!