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