WordPress and JWT with custom API Rest Endpoint WordPress and JWT with custom API Rest Endpoint wordpress wordpress

WordPress and JWT with custom API Rest Endpoint


You should add permission_callback parameter when registering a new route.

    add_action('rest_api_init', function ($data) {        register_rest_route('mladi-info/v1', '/user/favorites',             array(                'methods' => 'GET',                'callback' => 'mi_get_favorite_posts',                'permission_callback' => function ($request) {                        if (current_user_can('edit_others_posts'))                        return true;                 }             )        );    });

JWT Auth plugin will supply user object to permission_callback function, based on the token value from the header, and all you need to do is to work out some "permission logic" inside that function, which will return a bool value.

In the solution that I posted, callback allows access to REST endpoint only if the user that accessed it, has 'edit_others_posts' capability - which is the case for administrators and editors.


The actual way to use the JWT-auth plugin when it comes to protecting a endpoint is just prefixing it with the right namespace, then you send a Bearer header token so that can successfully access the resource.

In your case it would be:

add_action('rest_api_init', function ($data) {    register_rest_route('jwt-auth', 'mladi-info/v1/user/favorites', [        'methods' => 'GET',        'callback' => 'mi_get_favorite_posts'    ]);});

Then simply send an authenticated request towards that endpoint remember to send your Bearer token you got by using the /token endpoint (the one you send your username and password to get back the jwt token) in your headers. ie.

fetch('https://your-domain.com/wp-json/jwt-auth/mladi-info/v1/user/favorites', {    method: 'GET'    mode: 'cors',    headers: {      'Authorization': `Bearer ${jwt-token}`    },});