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 ....?

douyuqing_12345
douyuqing_12345 单击编辑将错误消息和任何其他信息放入您的问题。
一年多之前 回复
dpx86402
dpx86402 我刚做了一个测试:publicstaticfunctiontest_authorized($group){global$wpdb;$current_user=wp_get_current_user();echo'----------'。$current_user->user_nicename。'--------';[...]}以下是答案:{“readyState”:4,“responseText”:“................{”code“:”rest_forbidden“,”消息“:”抱歉,您不能这样做。“,”数据“:{”状态“:401}}”,“状态”:401,“statusText”:“未经授权”}所以我的印象是添加过滤器时用户设置不正确。但为什么它适用于邮递员......?
一年多之前 回复
drvxnivoqf17568697
drvxnivoqf17568697 {“readyState”:4,“responseText”:“{”code“:”rest_forbidden“,”message“:”抱歉,您不能这样做。“,”数据“:{”状态“:401}}”,“状态”:401,“状态文本”:“未授权”}
一年多之前 回复
doulu1325
doulu1325 你介意告诉我们问题是什么吗?是否有任何错误信息?
一年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐