WordPress REST API | What is it and How to Secure WP REST APIs



 What is WordPress REST API?

  • The WordPress REST API (Representational State Transfer Application Programming Interface) provides an interface for applications (Like Android, IOS, React, Angular) to interact with your WordPress website by sending and receiving data as JSON (JavaScript Object Notation) objects.
  • Here, We use JavaScript to visit the WordPress REST API so as to load content from the WordPress database into our webpage.
  • Example: The below REST endpoint is used to fetch all the WordPress posts and pages.
    • GET /posts - https:///wp-json/wp/v2/posts

      GET /pages - https:///wp-json/wp/v2/pages


 What is REST?

  • REST, or REpresentational State Transfer, are basically the collection of JSON endpoints (URLs) which contain the information regarding your posts, pages. You can simply make a GET request to your endpoint and read your website content in JSON format. This makes WordPress REST API available for CRUD operations allowing you to conveniently Create, Read, Update and Delete content on your site from outside the WordPress installation.

 What is API?

  • An API or Application Programming Interface allows two applications to communicate with each other. Each time a user sends a request to the server. The server responds to that request with a resource fetched from the server called response. The API is created on the server and the user is allowed to talk to it. This provides an interface for the computer systems on the web, making it easier for client and server to interact with each other and share data in limited, clearly defined ways.
  • API allows the user to send or receive data by making a particular "call" or "request." JSON is a programming language that is used for this communication. API can be used to make four different types of requests:
    1. 1. GET (Retrieve)

      2. POST (Create)

      3. PUT (Update)

      4. DELETE (Remove)


 Everyday Examples of API:

      1. Weather Forecast : Weather APIs are Application Programming Interfaces that allows you to fetch data from the large databases of weather forecasts. This is done by the means of an API, which delivers the response back to you.

      2. Google Map : Google Maps API is useful in providing the data like Geo locations, Latitudes, Longitudes, etc from the Google map database.


 How is WordPress REST API Useful?

  • The WordPress REST API makes CRUD (Create, Read, Update & Delete) operations available from anywhere instead of being limited to just the admin dashboard. It provides the lightweight form of communication between the client and the server making it a great solution for exchanging data.
  • It can be used to create iOS/Android,etc native apps. We can use any language we want as long as the language has the ability to make HTTP requests and interpret JSON such as Node,js, Express.js, Ruby, Python etc.

 Why do you need to protect/secure your REST APIs?

  • Open access APIs/Public APIs - WordPress REST APIs are by default open and it’s accessible without any authentication method. In which If someone tries to access the users API then he can easily access the WordPress admin user.
  • Example: You can try the below endpoint in the browser.

      https:///wp-json/wp/v2/users


  • WordPress Rest API - Secure rest api

 How to protect/secure your WordPress REST APIs?

  • You can secure your WordPress REST APIs using WordPress REST API Authentication plugin, It provides a feature called Protected REST APIs which you can configure to protect your REST APIs.

  • WordPress Rest API - protected rest apis

 Use cases for WordPress REST APIs

There are many different use cases available for WordPress REST APIs and some of the main use-cases of it are listed below.

    1. Suppose you want to develop a Android and IOS application and It’s a simple Blog application where users can see the blogs and post the blogs using the mobile application itself. Now in that case you want to create, retrieve, update and delete the posts from the mobile application too. Which could be done easily by help of WordPress.


    WordPress Rest API - mobile application using WordPress Rest API

    2. Suppose you already have an ecommerce site which is developed with help of WooCommerce plugin and WordPress and you are looking for developing the native applications using the React framework.

    Now, you don’t want to go with create another database for the native application and upload all the products, customer and order details approach as it won’t be efficient and well maintained according to the case of WordPress.

    You can easily access the WooCommerce REST APIs into your native application even with the functionality of login of the user with WordPress credentials and even if with the social login.

    You can easily authenticate and access the WooCommerce REST APIs If you have logged in using the social login platform into your application.


    WordPress Rest API - Woocommerce Rest Api

 How the WordPress REST APIs Works

  • Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.
  • However, the REST API includes a technique called nonces to avoid CSRF issues. This prevents other sites from forcing you to perform actions without explicitly intending to do so. This requires slightly special handling for the API.
  • I would suggest you to download the WP REST API Authentication plugin which will make a lot easier to access the WordPress REST APIs according to your use-case or requirements.

  • WordPress Rest API - Wordpress rest API Authentication
  • It supports a lot of authentication methods like API Key Authentication,Basic Authentication,JWT Authentication,OAuth 2.0 Authentication and Third Party OAuth 2.0 Provider Authentication method etc. Which is compatible with all the below HTTP methods.
    1. 1. GET (Retrieve)

      2. POST (Create)

      3. PUT (Update)

      4. DELETE (Remove)

  • Once you installed the plugin you can enable the API Key Authentication method as in the below screenshot.

  • WordPress Rest API - API Key Authentication
  • After that you would be able to access the WordPress REST APIs with the given API key from the plugin.
  • But wait how you gonna test it?

  • You can use ready made tools to access the WordPress REST APIs like Postman, Rested (Chrome extension) and Curl commands etc.
  • So, you can run the below curl command to retrieve the posts from the WordPress.
  • Curl -H ‘Authorization: Bearer ’ -X GET https:///wp-json/wp/v2/posts
  • You just need to replace the API-key and the domain for your WordPress site and you will retrieve all the posts in the response.

 Access WordPress REST APIs using postman

  • Postman is a software development tool. It enables people to test calls to APIs. You can access the WordPress posts using the postman as below step.
  • Select the GET method and enter your domain in the url field. After that go to Headers tab and add Authorization header and it’s value Bearer . Once you enter all the details click on the send button just like below screenshot.
  • WordPress Rest API - WordPress REST API using Postman
  • Similarly you can make all the HTTP method requests like POST, PUT and DELETE using postman. This plugin provides a developer documentation as well where you can get all the curl command and postman samples for accessing the WordPress REST APIs with all the authentication methods it supports. You just need to run it.
  • https://developers.miniorange.com/docs/rest-api-authentication/wordpress/api-key-authentication

 Create your Own WordPress REST APIs

  • WordPress provides some by default REST endpoints to get the resources. Some of the below objects are:
    1. 1. Posts

      2. Pages

      3. Media

      4. Post Meta

      5. Comments

      6. Users

      7. Terms


 What if you want to get your custom data from the database using REST APIs?

  • In this case you need to create custom WordPress REST APIs to handle the functionality or you can use the below plugin to make custom WordPress REST APIs.

  • WordPress Rest API - Download Custom API for WP plugin
  • You can simply put the API name and the HTTP method you want to use. After that, you need to select the database table from which you want to retrieve the data. You can also select the columns and make the condition to get it without even coding a single line.

  • WordPress Rest API - Custom API for WP plugin

 WordPress REST API Authentication Methods in our WordPress plugin:

  • Basic Authentication
    • 1. Username:Password

      2. Client-ID:Client-Secret

  • API Key Authentication
  • JWT Authentication
  • OAuth 2.0 Authentication
    • 1. Password Grant

      2. Client Credentials Grant

  • Third Party Provider Authentication

     Applications/Use-Cases:

    1. Basic Authentication: If you want to protect your WP REST APIs(eg. post, pages and other REST APIs) with users login credentials or client-id:client-secret, then you can opt for this method. It is recommended that you should use this method on HTTPS or secure socket layer.

    2. API Key Authentication: If you want to protect your WP REST APIs(eg. post, pages and other REST APIs) from unauthenticated users but you don’t want to share users login credentials or client id, secret to authenticate the REST API, then you can use API Key authentication, which will generate a random authentication key for you. Using this key, you can authenticate any REST API on your site.

    3. JWT Authentication If you are looking to protect your REST APIs using the JWT token and if you do not have any third party provider/identity provider that issues the JWT token, then you should go for JWT Authentication method. In this case, our WordPress REST API Authentication itself issues the JWT token and works as an API Authenticator to protect your REST APIs.

    4. OAuth 2.0 Authentication: If you are looking for protecting your REST APIs using the access-token and at the same time you do not have any third party provider/identity provider, then you should go for OAuth 2.0 Authentication method. In this scenario, our WordPress REST API Authentication works as both OAuth Server and API Authenticator to protect your REST APIs.

    5. Third Party Provider Authentication: If you are looking for protecting/restricting access to your WP REST APIs using your OAuth Provider/Identity provider, then you should go for Third Party Provider Authentication method.
    6. Here, you just need to configure the plugin with Introspection Endpoint/User Info Endpoint provided by your Identity Provider and you will be able to authenticate the API Request using the token provided by your provider application.

     Basic Authentication:

    • Basic Auth using UserName & Password :
      • 1. Select your Authentication method ->Basic Auth and Authentication Key -> Username:Password and click on Save Configuration as shown     below.



        2. After you save the Basic Auth Configuration, to access the WordPress site, you need to send an API request with your respective Authorization     Key. You need to use the request format as shown below.

      Request: GET https://<domain-name>/wp-json/wp/v2/posts
      Header: Authorization : Basic base64encoded <username:password > 
      
      Sample request: GET https://<domain-name>/wp-json/wp/v2/posts Header: Authorization : Basic eGw2UllOdFN6WmxKOlNMRWcwS1ZYdFVrbm5XbVV2cG9RVFNLZw==
    • Basic Auth using Client-ID & Client Secret :
      • 1. Select your Authentication method ->Basic Auth and Authentication Key -> Client-ID:Client-Secret and click on Save Configuration as     shown below.



        2. After you save the Basic Auth Configuration, user need to send a API request with your respective Authorization Key to access the WordPress site.     You need to use the request format as shown below.

      Request: GET https://<domain-name>/wp-json/wp/v2/posts
      Header: Authorization : Basic base64encoded <client-id:client-secret> 
      
      Sample request: GET https://<domain-name>/wp-json/wp/v2/posts Header: Authorization : Basic eGw2UllOdFN6WmxKOlNMRWcwS1ZYdFVrbm5XbVV2cG9RVFNLZw==

     API Key Authentication

        1. Select your Authentication method ->API Key and click on Save Configuration as shown below.



        2. Once you save the configuration, you will get the option to Generate New Token, click on Generate New Token button. This token will get     expired when you generate a new token.

        3. Once you generate the API Key(token), you can use it to secure your WordPress page / post.

        4. Users who have this token can access API as shown below.

      Request: GET https://<domain-name>/wp-json/wp/v2/posts
      Header: Authorization : Bearer <token> 
      
      Sample request: GET https://<domain-name>/wp-json/wp/v2/posts Header: Authorization : Bearer kGUfhhzXZuWisofgnkAsuHGDyfw7gfhg5s

     JWT Authentication

      1. Select your Authentication method ->JWT Authentication and click on Save Configuration as shown below.



      2. Here you would need to make two calls:

        i. To get the JWT Token
        ii. To Send an API Request

      Step 1 : Get the JWT Token

      • To get the JWT Token, you would need to make an API Call to Token endpoint as below

        Request:
        POST https://<domain-name>/wp-json/api/v1/token
        Body:
        username = < wordpress username >
        &password = < wordpress password >
        

      Step 2 : Send API Request

      • Once you get the JWT token, you can use it to request the access to the WordPress site as shown below.

        Request:
        GET https://<domain-name>/wp-json/wp/v2/posts
        
        Header:
        Authorization : Bearer < JWT token >
        

      Note : Above token is valid for 1 hour. Users have to create a token each time they want to request the API access.

     OAuth 2.0 Authentication

    • OAuth 2.0 using Password Grant :
      • 1. Select your Authentication method ->OAuth 2.0 and OAuth 2.0 Grant Type -> Password Grant & Token Type->Access Token/JWT Token     based on your choice and click on Save Configuration as shown below.



        2. Once you click on the save configuration, you will get the Client ID, Client Secret & Token Endpoint.

        3. Here you would need to make two calls:

          i. To get the Token
          ii. To Send an API Request

        Step 1 : Get the Token

        • To get the access token/JWT Token, you would need to make an API Call to Token endpoint as below

          Request:
          POST https://<domain-name>/wp-json/api/v1/token
          Body:
          grant_type = < password >
          &username = < wordpress username >
          &password = < wordpress password >
          &client_id = < client id >
          
        • Using Refresh Token

          Request:
          POST https://<domain-name>/wp-json/api/v1/token
          Body:
          grant_type = < refresh_token >
          &refresh_token = < Refresh Token >
          

        Step 2 : Send API Request

        • Once you get the access_token / id_token, you can use it to request the access to the WordPress site as shown below.

          Request:
          GET https://<domain-name>/wp-json/wp/v2/posts
          
          Header: Authorization : Bearer < access_token / id_token >

        Note : Above token is valid for 1 hour. Users have to create a token each time they want to request the API access.

    • OAuth 2.0 using Client Credentials Grant :
      • 1. Select your Authentication method ->OAuth 2.0 and OAuth 2.0 Grant Type -> Client Credentials Grant & Token Type->Access Token/JWT     Token based on your choice and click on Save Configuration as shown below.



        2. Once you click on the save configuration, you will get the Client ID, Client Secret & Token Endpoint.

        3. Here you would need to make two calls:

          i. To get the Token
          ii. To Send an API Request

        Step 1 : Get the Token

        • After saving above configuration, you will get the Client ID, Client-Secret & Token Endpoint.
        • To get the token, you need to send a token request as shown below

          Request:
          POST https://<domain-name>/wp-json/api/v1/token
          Body:
          grant_type = < client_credentials >
          &client_id = < client id >
          &client_secret = < client secret >
          
        • Using Refresh Token

          Request:
          POST https://<domain-name>/wp-json/api/v1/token
          Body:
          grant_type = < refresh_token >
          &refresh_token = < Refresh Token >
          

        Step 2 : Send API Request

        • Once you get the access_token / id_token, you can use it to request the access to the WordPress site as shown below.

          Request:
          GET https://<domain-name>/wp-json/wp/v2/posts
          
          Header:
          Authorization : Bearer < access_token / id_token >
          

        Note : Above token is valid for 1 hour. Users have to create a token each time they want to request the API access.

     Authentication using Third Party Provider

        1. Select your Authentication method ->Third party Provider and add Introspection Endpoint provided by your OAuth/OpenID Connect provider     and click on Save Configuration as shown below.


        2. Once you configure the plugin with Introspection Endpoint provided by your provider, try to access your WordPress page/posts using the access     token/id_token provided by your OAuth Provider as shown below.

        Request:
        GET https://<domain-name>/wp-json/wp/v2/posts
        
        Header:
        access_token : < access_token >
        OR id_token : < id_token >
        
Hello there!

Need Help? We are right here!

support
Contact miniOrange Support
success

Thanks for your inquiry.

If you dont hear from us within 24 hours, please feel free to send a follow up email to info@xecurify.com