0

I have a Plugin similiar to woocommerce which is providing me an REST API Endpoint for getting some user specific data.

When I try to access the API via Postman, i get an 401 - Not Authorized Error.

Of course, i have to authenticate my user to the api but how?

I found this (and many similar) posts to this topic: How to: Make JWT-authenticated requests to the Wordpress API

But all these examples seems to be for remote applications.

In my case, i want to use the api from my backend code.

And the page where i want to display the information (gathered from api) is only accessable for logged in users.

So i want to make an api call, for the current logged in user. This should happen automatically. Cant manually create keys for each user who wants to use the api, all users should have access.

Can i use the approach in the link or is there an better way to do this?

1

I solved my problem.

This got me on the right track: https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

You can just make an api call via frontend and jquery.

$.ajax( {
    url: '<?php echo esc_url_raw( rest_url()) ?>' + 'your/endpoint',
    method: 'GET',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', '<?php echo wp_create_nonce( 'wp_rest')?>' );
    }
} ).done( function ( response ) {
    console.log( response );
} );

If you want to outsource the script in an separate file you have to use wp_localize_script to pass the url base address and the nonce.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.