从本地主机到REST API的身份验证结果出现CORS错误。

4
我刚在一个开发服务器上安装了全新的wp。我正在尝试使用位于我的计算机/设备上的ionic/angularjs应用程序对rest api进行身份验证(插件,因为它是wp v.4.6.3)。目前正在使用JWT Authentication for WP-API插件。这是我的头信息,借助HTTP Headers插件:
content-encoding: gzip
x-powered-by: php/5.5.9-1ubuntu4.21
connection: keep-alive
content-length: 3361
keep-alive: timeout=5, max=95
access-control-allow-headers: accept, authorization, cache-control, cookie, content-type, origin
server: apache/2.4.7 (ubuntu)
x-frame-options: allow-from *
vary: accept-encoding
access-control-allow-methods: get, post, options, head, put, delete, trace, connect, patch
content-type: text/html; charset=utf-8
access-control-allow-origin: *
access-control-expose-headers: cache-control, cookie, content-type, origin
cache-control: no-cache, must-revalidate, max-age=0

无论我做什么都会出现CORS错误。最近的一个错误是:
请求头字段Content-Type在预检响应中不被Access-Control-Allow-Headers允许。
JWT插件的文档中还提到了编辑.htaccess和wp-config.php文件,我也确实进行了操作。尝试了几种htaccess编辑和/或插件的组合。但是依然出现相同或类似的错误。
以下是我的代码,基于JWT插件的文档(凭据/URL有效!):
var apiHost = 'http://dev.imok.ro/authworks/wp-json';
$http.post( apiHost + '/jwt-auth/v1/token', {
   username: 'admin',
   password: 'admin!@#'
})
.then( function( response ) {
   console.log( 'siker', response.data )
})
.catch( function( error ) {
   console.error( 'Errorrrr', error );
});

.htaccess:

#<ifModule mod_headers.c>
#    Header always set Access-Control-Allow-Origin: *
##    Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
##    Header always set Access-Control-Allow-Headers "content-type"
#</ifModule>

<IfModule mod_rewrite.c>

#SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

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

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

感谢您的帮助! Magor

对我来说是同样的问题 - Simon H
1个回答

2
您可以通过编辑 public/class-jwt-auth-public.php 来解决此问题。
public function add_cors_support()
{
    $enable_cors = defined('JWT_AUTH_CORS_ENABLE') ? JWT_AUTH_CORS_ENABLE : false;
    if ($enable_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, POST, UPDATE, DELETE' );
            header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );
            header( 'Access-Control-Allow-Credentials: true' );
            return $value;
        });

        // $headers = apply_filters('jwt_auth_cors_allow_headers', 'Access-Control-Allow-Headers, Content-Type, Authorization');
        // header(sprintf('Access-Control-Allow-Headers: %s', $headers));
    }
}

我已提交了一个PR。PR的详细信息请查看此链接

我不是幸运的,它不起作用。 - DMS-KH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接