Search code examples
ajaxwordpressrestful-authentication

Secure REST API token in a JavaScript AJAX call


I need to pull data from a 3rd-party REST API into a WordPress page. It's a search app so I would like to avoid page refresh and load results via AJAX if possible.

The API setup is as follows:

  • User/password is required to get a bearer token (POST request, separate endpoint)
  • Bearer token is required for every GET request to the API
  • Token expires every 30 days

What are best practices for securing login credentials and token in a front-end application?

Even if authentication is handled on the server using wp_remote_post, how do I pass the token value to JavaScript without exposing it in the browser?


Solution

  • It would be best to build a wrapper server-side, for the exact reason you mention in your Q. You don't want to expose your bearer token on the front end!

    add_action('rest_api_init', function () {
      register_rest_route('user5050800/v1', '/search', [
        'methods' => 'GET',
        'callback' => 'search_wrapper',
      ]);
    });
    
    function search_wrapper(WP_REST_Request $request) {
      try {
        // make the req
        wp_remote_post($request->get_query_params()); // or something
      } catch (\WP_Error $e) {
        // figure out if it's a 403, or if you might need to make an additional req to get a new token and try again
      }
    }