Client Credentials Grant

Token Request

To receive an access token, the client POSTs an API call with the values for client ID and client secret obtained from a registered developer app as follow.

      POST http://<wp_base_url>/wp-json/moserver/token
      Content-Type: application/x-www-form-urlencoded

      grant_type=client_credentials&
      client_id={client_id}&
      client_secret={clientSecret}&
      redirect_uri=<redirect_uri>&
      scope=<permisssions_requested>

Request Parameters :
The POST request parameters are explained below.

  • grant_type=client_credentials : This tells the server we’re using the client credentials grant type.

  • client_id : The public identifier of the application that the developer obtained during registration.

  • client_secret : The client secret provided by the OAuth provider.

  • redirect_uri : Callback Url to which user will be redirected once they allow or disallow the access to your app.

  • scope : One or more space seperated strings which indicates the permission your application requesting.

  • cURL
  • Postman
  • C#
  • Java
  • PHP
  • Python
curl -H "Content-Type:application/x-www-form-urlencoded" -d "grant_type=client_credentials&client_id=<your-client-id>&client_secret=<your-client-secret>" http://<your-wordpress-domain-name>/wptest/wordpress/wp-json/moserver/token

Click here to download POSTMAN collection export

String getAccessToken()
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://YOUR_DOMAIN/wp-json/moserver/token");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Method = "POST";
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = JsonConvert.SerializeObject(new
        {
            grant_type = "client_credentials",
            client_id = "<<YOUR CLIENT_ID>>",
            client_secret = "<<YOUR CLIENT SECRET>>"
        });
        streamWriter.Write(json);
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    var streamReader = new StreamReader(httpResponse.GetResponseStream());
    var result = streamReader.ReadToEnd();
    dynamic jtoken = JsonConvert.DeserializeObject(result);
    Console.WriteLine(jtoken.access_token);
    return jtoken.access_token;
}
private String getAccessToken(clientId, clientSecret)
{
        Pattern pat = Pattern.compile(".*\"access_token\"\\s*:\\s*\"([^\"]+)\".*");
        String content = "grant_type=client_credentials&client_id=" +clientId+"&client_secret="+clientSecret;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        String accesstoken = "";
        try {
        URL url = new URL(tokenUrl);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + authentication);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "application/json");
        PrintStream os = new PrintStream(connection.getOutputStream());
        os.print(content);
        os.close();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        StringWriter out = new StringWriter(connection.getContentLength() > 0 ? connection.getContentLength() : 2048);
        while ((line = reader.readLine()) != null) {
                out.append(line);
        }
        String response = out.toString();
        Matcher matcher = pat.matcher(response);
        if (matcher.matches() && matcher.groupCount() > 0) {
                accesstoken = matcher.group(1);
        }
        connection.disconnect();
        } catch (Exception e) {
        System.out.println("Error : " + e.toString());
        } finally {
        if (reader != null) {
                try {
                reader.close();
                } catch (IOException e) {
                }
        }
        }
        System.out.println(accesstoken);
        return accesstoken;
}
function getAccessToken() {
    $token_url = "http://YOUR_DOMAIN/wp-json/moserver/token";
    $client_id = "<YOUR CLIENT_ID>";
    $client_secret = "<YOUR CLIENT SECRET>";
    $content = "grant_type=client_credentials";
    $authorization = base64_encode("$client_id:$client_secret");
    $header = array("Authorization: Basic {$authorization}","Content-Type: application/x-www-form-urlencoded");
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $token_url,
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $content
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    echo $response;
    return json_decode($response)->access_token;
}
import requests, json
def get_access_token():
    token_url = "http://YOUR_DOMAIN/wp-json/moserver/token"
    client_id = '<<CLIENT_ID>>'
    client_secret = '<<CLIENT SECRET>>'
    data = {'grant_type': 'client_credentials'}
    access_token_response = requests.post(token_url, data=data, verify=False, allow_redirects=False, auth=(client_id, client_secret))
    print access_token_response.headers
    print access_token_response.text
    tokens = json.loads(access_token_response.text)
    access_token = tokens['access_token']
    print "access token: " + access_token
    return access_token

If the credentials are valid, the application will receive back a signed JSON Web Token or access token, the token's type (which is Bearer), and in how much time it expires in Unix time.

Sample Response:

        {
          "access_token": <access_token>,
          "expires_in": 600,
          "token_type": "Bearer"
        }

Response Elements :

  • access_token : access token for the Userinfo endpoint.
  • expires_in : The expiry time for the access token.
  • token_type : OAuth 2.0 token type value. The value must be Bearer.