WordPress and JWT with custom API Rest Endpoint

Viewed 4613

I need to provide a plugin for WordPress that will have few custom API endpoints, and I have installed these two plugins

I have created custom endpoint:

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

I need to protect this endpoint so that only those requests that has JWT token sent (generated with /wp-json/jwt-auth/v1/token endpoint sending username and password) can be processed, otherwise it should return 401 status codes. How do I do that?

2 Answers

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}`
    },
});
Related