duanhuayong6687 2019-02-21 09:05
浏览 151

WordPress JWT - 错误验证(401)

I just discovered WordPress a short time ago, and encounter some problems when using JWT with a custom endpoint.

Indeed, after having correctly configured my API and JWT, I encounter an authentication problem during my AJAX request.

What seems strange to me is that I have no problem using Postman. So I think it's a WordPress configuration problem ...

Here is an overview of my code, which I have shortened, and made as clear as possible for the occasion.

Configuration of JWT:

(.htaccess)

...
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>
...

(wp-config.php)

...
define('JWT_AUTH_SECRET_KEY', 'secretKey...');
define('JWT_AUTH_CORS_ENABLE', true);
...

Ajax (In my plugin folder)

jQuery.ajax({
        url: url + '/wp-json/test/v1/test_users' + order,
        type: 'GET',
        headers: 
        {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer myToken...'
        },

        success: function(data) {
            alert('success');
        },

        error : function(data) {
            alert(JSON.stringify(data));
        }
    });

Endpoint (In my child theme)

add_action( 'rest_api_init', function () {
            register_rest_route( 'test/v1', '/test_users', array(
                'methods' => 'GET',
                'callback' => array($this, 'get_users'),
                'permission_callback' => function () {
                    return Routes::test_authorized(5);
                }
            ) );
        });

public static function test_authorized($group)
{
    global $wpdb;
    $current_user = wp_get_current_user();

    if (empty($current_user))
        return false;

    $user = ...

       ...

    if (empty($user) || $user == null || $user->test_group > $group)
        return false;

    return true;
}

nonce

add_action('rest_api_init', function () {
            add_filter('jwt_auth_token_before_dispatch', function ($data, $user) {
            // Tells wordpress the user is authenticated
            wp_set_current_user($user->ID);
            $data['nonce'] = wp_create_nonce('wp_rest');
            return $data;
            }, 10, 2);
        });

Thank you !

EDIT :

Error message :

{"readyState":4,"responseText":"{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}}","status":401,"statusText":"Unauthorized"}

I just did a test :

public static function test_authorized($group)
{
        [...]

        echo '----------' . $current_user->user_nicename . '--------';

        [...]
}

And here is the answer :

{"readyState":4,"responseText":"---------------------------{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}}","status":401,"statusText":"Unauthorized"}

So I have the impression that the user is not well set when adding the filter. But why does it work on postman ....?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥50 树莓派安卓APK系统签名
    • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
    • ¥65 汇编语言除法溢出问题
    • ¥15 Visual Studio问题
    • ¥20 求一个html代码,有偿
    • ¥100 关于使用MATLAB中copularnd函数的问题
    • ¥20 在虚拟机的pycharm上
    • ¥15 jupyterthemes 设置完毕后没有效果
    • ¥15 matlab图像高斯低通滤波
    • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗