Screenshot WOW SAVE 20% on the All Access Bundle. Use "OAUTH20OFF" at checkout.
GET DEAL
3rd Party Integration

Using a Bearer Token with WP REST API

Published: October 4, 2018 | Updated: December 31st, 2019
  1. Home
  2. Docs
  3. How To
  4. Using a Bearer Token with WP REST API

Overview

In some cases, you may feel more comfortable using a Bearer Token for Authorization. Sending an access token as a Bearer Token is useful when you want to conceal the access token in a request header instead of sending it to in the body or request. Sending a bearer token is simple and if you are familiar with basic authorization then bearer token will make a lot of sense. To send a bearer token for authorization against a protected resource send only one Authorization header in the following format:

Authorization: Bearer pwwbkvv7abqzonnvztpea91ich7vprwdorbt4w4m

When you send a bearer token you can not send any other authorization header. OAuth2 specification state that only one authorization header can be used. If more than 1 authorization header is presented at the same time then a 400 Bad Request should be presented.

PHP Curl Example

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://wordpress.dev/wp-json/wp/v2/posts/1178/revisions/",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "authorization: Bearer pwwbkvv7abqzonnvztpea91ich7vprwdorbt4w4m",
    "cache-control: no-cache"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}


jQuery AJAX Example

var access_token = 'pwwbkvv7abqzonnvztpea91ich7vprwdorbt4w4m';
jQuery.ajax( {
    url: 'https://{your-server-url}/me/',
    type: 'POST',
    data: { content: 'testing testing' },
    beforeSend : function( xhr ) {
        xhr.setRequestHeader( 'Authorization', 'BEARER ' + access_token );
    },
    success: function( response ) {
        // response
    }
} );
Icon