Search Results :

×

WordPress REST API Key Authentication Method | Secure REST API


WordPress REST API key authentication involves verifying the API key (Bearer token) to gain access to the WP REST APIs. Each time a request is initiated to access WP REST API endpoints, authentication is necessary using the key (Bearer token). Access to resources for the requested WordPress REST API endpoint is granted based on the validation of the API key (Bearer token).

For the record, the API key is an authentication protocol designed to allow developers to generate authentication keys that could be used for resources such as server-side processes, mobile phone applications, and desktop computers.

The WordPress API key authentication method is a vital means to ensure the security of your WordPress REST API. If the API key becomes compromised, it can be regenerated, causing all previously generated keys to expire automatically. The newly created key will then be employed for WP API Key Authentication. Failing to secure your REST API can pose significant security risks, as it can provide unauthorized individuals with access to your system, potentially leading to data breaches.

This guide will walk you through a detailed, step-by-step process for installing and configuring WordPress REST API Authentication to enhance the security of your REST API.




WordPress Rest API Authentication
By miniOrange

WordPress REST API Authentication plugin provides the security from unauthorized access to your WordPress REST APIs.

Know More

Steps to Download & Installation

  • Log into your WordPress account as an admin.
  • Go to the WordPress Dashboard -> Plugins and click on Add New.
  • Search for a WordPress REST API Authentication plugin and click on Install Now.
  • Once installed click on Activate.

idp_sso_image1 Use Case: Protect/Secure WordPress REST API Endpoints Access via Bearer Key/Token


WordPress REST API Authentication key method

    1.  API Key authentication can serve as a safeguard for your WordPress REST API Endpoints, such as posts, pages, or any other REST APIs of WordPress, shielding them from unauthorized access and negating the need to share a user's WP login credentials or client ID and client secret for authentication. This WordPress API key generator approach creates a unique authentication key, which you can utilize to authenticate various WordPress REST APIs on your website.

    Utilizing the WordPress REST API key authentication represents one of the easiest and most widely adopted approaches to fortifying your WP REST API with API key authentication. This approach enhances the security of REST APIs on your WordPress website.


    2.   Imagine you've developed a Blog Application for Android and iOS, and you've published all your blogs on WordPress. However, you'd like to retrieve the posts/blogs from WordPress REST APIs while keeping them inaccessible to the public. In such cases, it's advisable to implement WordPress REST API Key Authentication to safeguard your GET requests, ensuring the security of your endpoints.


idp_sso_image1  The plugin provides two kinds of API keys/ security tokens that can be used to authenticate WordPress REST APIs -


    I.   Universal API Key - The Universal API key will be most suitable to authenticate the WP REST APIs, which involve the HTTP GET method and do not require WordPress user capabilities.


    Please note: This key does not involve user capabilities and cannot be used to access those APIs for which WordPress expects user permissions. “Example - If you just want to use the GET APIs for fetching general WordPress posts, comments, etc.”


    II.   User-specific API Key - The user-based API will be the most suitable to authenticate the WP REST APIs that involve any of the HTTP methods like - GET, POST, PUT, DELETE, especially in those cases in which you want to perform operations that involve user capabilities.


    Example - If you want to perform any operations like fetching WordPress posts based on user capabilities (their WP roles), user data, or want to create new users, new posts, etc.


idp_sso_image1 Read Use Cases for the following Rest API Authentication Methods:

1. Setup WordPress API Authentication Plugin [Premium]


    WordPress REST API Authentication key method
  • In the plugin, go to the Configure API Authentication tab and click on API Key Authentication as the API Authentication method.
  • Once you save the configuration, Under the Universal API key section you will get the option to Generate New Token, Click on Generate New Key button. This key/token will expire when you generate a new key/token.
  • Once you generate the API key (token), you can use it to secure your WordPress REST API endpoints. (You can always generate the new API key, and all the existing generated keys will expire automatically).
  • You need to pass the API Key to the Authorization header as a bearer token while making the REST API request to your WP site, as shown in the step below.
  • Users who have this token can access the REST 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
    
      Sample curl Request Format-
      curl -H "Authorization:Bearer <token-value>"
      -X GET http://<wp_base_url>/wp-json/wp/v2/posts
      
  • The Header is explained below.
  •    I. Authorization : The HTTP Authorization request header typically includes the user agent's credentials or token type and token value, serving as a means to authenticate the user agent with a server. This commonly occurs following an unsuccessful authentication attempt, where the server responds with a status of 401 Unauthorized.

       II. Bearer <token-value>: The Bearer <token-value> is created by the Authentication server. When a client application requests the authentication server then the server authenticates that token and gives a response to the client application accordingly.

  • Check out the developer documentation for more details.
  • Check out the Error Response for API key Authentication.

miniorange img Code samples in programming languages


 
  var client = new RestClient("http://<wp_base_url>/wp-json/wp/v2/posts ");
  client.Timeout = -1;
  var request = new RestRequest(Method.GET);
  request.AddHeader("Authorization", "Bearer <token-value>");    
  IRestResponse response = client.Execute(request);
  Console.WriteLine(response.Content);
  
 
  OkHttpClient client  = new OkHttpClient().newBuilder().build();
  Request request  = new Request.Builder()
  .url("http://<wp_base_url>/wp-json/wp/v2/posts ")
  .method("GET", null)
   .addHeader = ("Authorization", "Bearer <token-value>")    
   .build();
  Response responseclient.newCall(request).execute();
          
 
  var settings  = {
      "url": "http://<wp_base_url>/wp-json/wp/v2/posts ",
      "method": "GET",
      "timeout": 0,
      "headers": {
          "Authorization": "Bearer <token-value >"
        },        
    };
    
    $.ajax(settings).done(function (response)  {
      console.log(response);
    });
    
 
  <?php
   $curl = curl_init();
  curl_setopt_array($curl, array 
      (  
        CURLOPT_URL => 'http://%3Cwp_base_url%3E/wp-json/wp/v2/posts',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
          'Authorization: Bearer <token-value>'
        ),
      
          ));          
        
  $response = curl_exec($curl);
  curl_close($curl);    
  echo $response;
          
 
  import http.client
  
  conn   = http.client.HTTPSConnection("<wp_base_url>")
  payload= "
  headers = {
      'Authorization': 'Bearer <token-value>'
  }
  conn.request("GET", "/wp-json/wp/v2/posts ", payload, headers)
  res= conn.getresponse()    
  data = res.read()    
  print (data.decode("utf-8"))   
  

idp_sso_image1 Postman Samples:

    Follow the steps below to make REST API request using Postman:

  • Download the POSTMAN collection export from here.
  • Import the downloaded JSON file into the Postman Application as shown below.
  • WordPress REST API Authentication key method postman import JSON file
  • Once you import the JSON file, click on the REST API request under the Collections as shown in the last figure. Now replace the <wp_base_url> with your Wordpress domain in the http://<wp_base_url>/wp-json/wp/v2/posts and replace the API <token-value> in the header with the token value as generated in the plugin.
  • Example:
  • WordPress REST API Authentication key method postman replace base url

idp_sso_image1 Feature Description

    1. Role-Based REST API Restrictions:

    This feature enables restricting REST API access according to user roles. You have the option to specify which roles should be permitted to access the requested resource through REST APIs. Therefore, when a user initiates a REST API request, their role is retrieved, and access to the resource is only granted if their role is included in the whitelist.


    How to configure it?

    • First, go to the plugin ‘Advanced Settings’ tab.
    • In the Role-based Restriction section, initially, all roles are granted access to the APIs by default. However, you can selectively limit access by enabling the checkbox next to the roles you wish to restrict.
    • WordPress REST API Basic Authentication method postman implementation
    • In the above screenshot, the subscriber role checkbox is enabled. So whenever an API request is made by the user with his role as subscriber then that user won’t be allowed to access the requested resource.

    Note: The Role-based restriction feature is valid for Basic authentication (Username: password), JWT method, OAuth 2.0 (Password grant), and API Key Auth (User-specific API key).


    2. Custom Header

    This feature provides an option to choose a custom header rather than the default ‘Authorization’ header. This will enhance security by introducing a custom-named header. If an individual attempts to send a REST API request with an 'Authorization' header, they will be unable to access the APIs.


    How to configure it?

    • First, go to the plugin ‘Advanced Settings’ tab.
    • Then in the ‘Custom Header’ section, you can edit the textbox to enter the custom name you want.
    • WordPress REST API Basic Authentication method postman implementation

    3. Exclude REST APIs

    This feature allows you to create a whitelist for your REST APIs, enabling direct access to them without the need for authentication. Consequently, all REST APIs included in this whitelist become publicly accessible.


    How to configure it?

    • First, go to the plugin ‘Advanced Settings’ tab.
    • Then in the ‘Exclude REST APIs’, you can enter your APIs in the prescribed format which needs to be whitelisted for public access.
    • WordPress REST API Basic Authentication method postman implementation
    • Example: Suppose you want to exclude the REST API ‘ /wp-json/wp/v2/posts’ then you have to enter ‘/wp/v2/posts’ in the textbox.

    4. Create User Specific API keys/tokens

    • This feature is available within the API key method, allowing tokens to be generated based on user-specific information rather than a randomly generated token which is a universal key.
    • When using the Universal API key/token, users may lack the necessary permissions to access specific WordPress REST APIs with request methods like POST, PUT, or DELETE. These APIs involve actions such as creating users, posts, pages, etc., which require specific user permissions or roles for operation. The limitation arises because the universal key is randomly generated and does not include user-specific details.
    • The User-based API key/token feature empowers users to utilize WordPress REST APIs with request methods like POST, PUT, and DELETE, which mandate user credentials or specific roles for functionality. When a WordPress REST API request is executed using the user-based key, the system retrieves the user's role and grants access solely if the user possesses the necessary permissions.
    • For Example: Only users with administrator and editor roles have permission to create/edit/delete a post.
    • So, if a request is made to this API to create/delete/edit the post, the API response will result in “You are not allowed to perform this operation”.
    • Now, if a request is made with the user-based token generated for the user that has an administrator or editor role, only they have access to this API and can operate (create/update/delete) via the API call.
    • How to use this feature:

    • Select the user from the dropdown and click on the Create API Key button.
    • WordPress REST API Basic Authentication method postman implementation
    • A pop-up will appear on the screen, you just need to click on the OK button to copy the token.
    • WordPress REST API Basic Authentication method postman implementation
    • Now this token can be used with the API request just like the universal key is used to make the API request.

    Congratulations! You have successfully configured the WordPress REST API Key Authentication using this guide. Now, your WordPress REST API endpoints are secure, and your data is protected from unauthorized access.

    miniorange img Additional Resources

    Need Help?

    Mail us on apisupport@xecurify.com for quick guidance (via email/meeting) on your requirement and our team will help you to select the best suitable solution/plan as per your requirement.

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