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条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 idea运行测试代码报错问题
    • ¥15 网络监控:网络故障告警通知
    • ¥15 django项目运行报编码错误
    • ¥15 请问这个是什么意思?
    • ¥15 STM32驱动继电器
    • ¥15 Windows server update services
    • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
    • ¥15 模糊pid与pid仿真结果几乎一样
    • ¥15 java的GUI的运用
    • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。