Search Results :

×

Guide to Secure WordPress REST APIs with Basic Authentication

WordPress Basic Authentication for REST APIs secures access to WordPress endpoints by validating API requests with a token generated from a username and password or client credentials. This authentication method confirms user identity when interacting with the web service, ensuring only authorized users can access the WordPress REST API.



The Basic Auth plugin in WordPress helps secure REST APIs by using Basic Authentication. With this method, every API request sends credentials (username or email and password) encoded in base64, ensuring secure communication between your WordPress site and external applications.


WordPress REST API Authentication

WordPress REST API Authentication plugin provides security from unauthorized access to your WordPress REST APIs. Our plugin provides multiple authentication methods like Basic Authentication, API Key Authentication, OAuth 2.0 Authentication, and JWT Authentication.

Know More   


To set up WP API Basic Auth, you need to install a WordPress REST API Authentication plugin. This plugin allows the WordPress REST API to accept Basic Authentication credentials for secure access.


Step-by-Step Guide:


  • Step 1: Install the Plugin - Search for "REST API Authentication for WP" in the WordPress plugin repository and install it. This plugin will enable the REST API Basic Authentication on your site.
  • Step 2: Activate the Plugin - Once installed, activate the plugin from your WordPress dashboard by going to Plugins → Installed Plugins and clicking "Activate" next to the REST API Authentication plugin.
  • Step 3: Configure Authentication - Open the plugin settings and follow the steps to configure Basic Authentication for your REST API. Navigate to the plugin's configuration page to set up your authentication method.


1. Using Username Password for Secure Interaction with WordPress REST API


If you're developing an Android or iOS app that allows users to post their own feeds or blogs, ensuring secure and authenticated interactions with WordPress REST API is crucial.

How to securely manage user authentication:

  • Use WordPress Basic Authentication: Implement the WordPress Basic Authentication REST API with users' usernames and passwords. This method ensures that requests made through your app are securely authenticated.
  • Authenticate User Requests: When a user logs into your app, a session is created and the user's credentials are sent in an encrypted format within the Basic Authorization header.
  • Manage Permissions: Based on the user's WordPress permissions, the REST API determines the actions they are allowed to perform and the content they can access. This helps control user capabilities and maintain secure interactions with your WordPress site.

By using WordPress Basic Authentication with user credentials, you ensure that each user's actions are properly authenticated and authorized, providing a secure environment for user-generated content.


WordPress REST API Basic Authentication method using user credentials

2. Using Client Credentials for Secure Interaction with WordPress REST API


If you have an Android or iOS app and need to interact with WordPress content through its REST API, it’s essential to protect your site from unauthorized access. Instead of using WordPress user credentials directly, which can be risky, you should opt for WordPress Basic Authentication with client credentials.

Here's how to securely use client credentials:

  • Obtain Client ID and Client Secret: Instead of exposing WordPress user credentials, generate a client ID and client secret for your app.
  • Send Secure Requests: When making API requests, include the client ID and client secret. These credentials are transmitted in an encrypted format within the Basic Authorization header.
  • Validation and Access: Once the WordPress REST API receives your request, it validates the client credentials. If validation is successful, you gain access to the API endpoints you need, while keeping your site secure.

By using client credentials, you ensure that your WordPress user information remains protected while still allowing your app to interact with your WordPress site efficiently.


WordPress REST API Basic Authentication method using client credentials

Using Basic Authentication with the REST API: Username & Password


  • In the plugin, go to the Configure Methods tab in the left section.
  • Click on Basic Authentication as the API Authentication method.
  • WordPress REST API Basic Authentication method using username-and-password
  • Select Username & Password with Base64 Encoding and click Next in the top right corner.
  • WordPress REST API Basic Authentication method using username-and-password
  • In order to test the functionality, Fill in the username and Password fields for an existing user.
  • WordPress REST API Basic Authentication method using username-and-password
  • You can edit the REST API endpoint to fetch details from that endpoint. Example: /pages endpoint has been selected here:
  • Click on the Test Configuration button, and verify the result shown on the screen.
  • Click the Finish button.
  • WordPress REST API Basic Authentication method using username-and-password

REST API Basic Auth using Client ID and Client Secret :


  • In the plugin, go to Configure API Authentication tab and click on Basic Authentication as the API Authentication method.
  • Now, Select the Client-ID: Client-Secret as the Basic Authentication Key Type and choose any of the available Encryption methods which depend on how you want to encode the user credentials. HMAC is the most secure among these and the recommended one.
  • Finally, click on Save Configuration so Basic Authentication for WordPress REST API Authentication will be enabled.
  • WordPress REST API Basic Authentication method using client-id and client-secret
  • After you save the REST API Basic Auth Configuration, to access the WordPress REST APIs, you need to send a REST 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 <client-id:client-secret>
    Sample Request Format- Example => Client ID : pSYQsKqTndNVpNKcnoZd and Client Secret : SrYPTViHdCbvkWyTfWrSltavTMeJjaOHCye
    
      Sample curl Request Format-
      curl -H "Authorization:Basic base64encoded <clientid:clientsecret>"
      -X POST http://<wp_base_url>/wp-json/wp/v2/users
      -d"username=test&email=test@test.com&password=test&name=test" 
      
  • PHP base64_encode(string) function for base64 encoding can be used as follows:
  •         
       base64_encode(‘pSYQsKqTndNVpNKcnoZd:SrYPTViHdCbvkWyTfWrSltavTMeJjaOHCye’) will results into 
      ‘cFNZUXNLcV RuZE5WcE5LY25vWmQ6U3JZUFRWaUhkQ2J2a1d5VGZXclNsdGF2VE1lSmphT0hDeWU=’ as output.
    Sample request: GET https://<domain-name>/wp-json/wp/v2/posts  Header: Authorization :Basic eGw2UllOdFN6WmxKOlNMRWcwS1ZYdFVrbm5XbVV2cG9RVFNLZw==
  • Check out the Error Response for Basic Auth using Client ID and Client Secret.
  • Check out the developer documentation for more details.


 
  var client = new RestClient("http://<wp_base_url>/wp-json/wp/v2/posts ");
  client.Timeout = -1;
  var request = new RestRequest(Method.POST);
  request.AlwaysMultipartFormData = true;
  request.AddParameter("title", "Sample Post");
  request.AddParameter("status", "publish");
  IRestResponse response = client.Execute(request);
  Console.WriteLine(response.Content);
  
 
  OkHttpClient client  = new OkHttpClient().newBuilder().build();
  MediaType mediaType = MediaType.parse("text/plain");
  RequestBody body  = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("title","Sample Post")
  .addFormDataPart("status", "publish") 
  .build();
  Request request  = new Request.Builder()
  .url("http://<wp_base_url>/wp-json/wp/v2/posts ")
  .method("POST", body)
   .build();
  Response responseclient.newCall(request).execute();
  
 
  var form = new FormData();
  form.append("title","Sample Post");
  form.append("status", "publish"); 
  
  var settings  = {
  "url": "http://<wp_base_url>/wp-json/wp/v2/posts ",
  "method": "POST",
  "timeout": 0,
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
  };
  
  $.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%20',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('title' => 'Sample Post','status' => 'publish'),
  ));
  
  $response = curl_exec($curl);
  curl_close($curl);    
  echo $response;
  
 
  import http.client
  import mimetypes
  from codecs import encode
  
  conn   = http.client.HTTPSConnection("<wp_base_url>")
  dataList= []
  boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
  dataList.append(encode('--' + boundary))
  dataList.append(encode('Content-Disposition: form-data; name=title;')) 
  
  dataList.append(encode('Content-Type: {}'.format('text/plain')))    
  dataList.append(encode(''))    
  
  dataList.append(encode("Sample Post"))
  dataList.append(encode('--' + boundary))    
  dataList.append(encode('Content-Disposition: form-data; name=status;'))    
  
  dataList.append('Content-Type: {}'.format('text/plain')))
  dataList.append(encode(''))    
  
  dataList.append(encode("publish")) 
  dataList.append(encode('--'+boundary+'--'))    
  dataList.append(encode(''))    
  body  = b'\r\n'.join(dataList)    
  payload= body
  headers = {
  'Content-type': 'multipart/form-data; boundary={}'.format(boundary) 
  }
  conn.request("POST", "/wp-json/wp/v2/posts ", payload, headers)
  res= conn.getresponse()    
  data = res.read()    
  print (data.decode("utf-8"))   
  
 
  var client = new RestClient("http://<wp_base_url>/wp-json/wp/v2/posts ");
  client.Timeout = -1;
  var request = new RestRequest(Method.POST);
  request.AddHeader("Authorization", "Basic base64encoded < clientid:clientsecret > ");
  request.AlwaysMultipartFormData = true;
  request.AddParameter("username", "test");
  request.AddParameter("email", "test@test.com");
  request.AddParameter("password", "test");
  request.AddParameter("name", "test");
  IRestResponse response = client.Execute(request);
  Console.WriteLine(response.Content);
  
 
  OkHttpClient client  = new OkHttpClient().newBuilder().build();
  MediaType mediaType = MediaType.parse("text/plain");
  RequestBody body  = new MultipartBody.Builder().setType(MultipartBody.FORM)
  .addFormDataPart("username","test")
  .addFormDataPart("email","test@test.com")
  .addFormDataPart("password","test")
  .addFormDataPart("name","test") 
  .build();
  Request request  = new Request.Builder()
  .url("http://<wp_base_url>/wp-json/wp/v2/posts ")
  .method("POST", body)
  .addHeader ("Authorization", "Basic base64encoded < clientid:clientsecret > ")
   .build();
  Response responseclient.newCall(request).execute();
  
 
  var form = new FormData();
  form.append("username", "test");
  form.append("email", "test@test.com");
  form.append("password", "test");
  form.append("name", "test");
  
  var settings  = {
  "url": "http://<wp_base_url>/wp-json/wp/v2/posts ",
  "method": "POST",
  "timeout": 0,
  "headers": {
  "Authorization": "Basic base64encoded < clientid:clientsecret > "
  },
  "processData": false,
  "mimeType": "multipart/form-data",
  "contentType": false,
  "data": form
  };
  
  $.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/users',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => array('username' => 'test','email' => 'test@test.com','password' => 'test','name' => 'test'),
  CURLOPT_HTTPHEADER => array(
  'Authorization: Basic base64encoded < clientid:clientsecret > '
  ),
  ))  
  $response = curl_exec($curl);
  curl_close($curl);    
  echo $response;
  
 
  import http.client
  import mimetypes
  from codecs import encode
  
  conn   = http.client.HTTPSConnection("<wp_base_url>")
  dataList= []
  boundary = 'wL36Yn8afVp8Ag7AmP8qZ0SA4n1v9T'
  dataList.append(encode('--' + boundary))
  dataList.append(encode('Content-Disposition: form-data; name=username;'))
  
  dataList.append(encode('Content-Type: {}'.format('text/plain')))    
  dataList.append(encode(''))    
  
  dataList.append(encode("test"))
  dataList.append(encode('--' + boundary))    
  dataList.append(encode('Content-Disposition: form-data; name=email;'))
  
  dataList.append('Content-Type: {}'.format('text/plain')))
  dataList.append(encode(''))    
  
  dataList.append(encode("test@test.com"))
  dataList.append(encode('--'+ boundary))    
  dataList.append(encode('Content-Disposition: form-data; name=password;'))
  
  dataList.append(encode('Content-Type: {}'.format('text/plain')))
  dataList.append(encode(''))
  
  dataList.append(encode("test"))
  dataList.append(encode('--' + boundary))
  
  dataList.append(encode('Content-Disposition: form-data; name=name;'))
  
  dataList.append(encode('Content-Type: {}'.format('text/plain')))
  dataList.append(encode(''))
  
  dataList.append(encode("test"))
  dataList.append(encode('--'+boundary+'--'))
  dataList.append(encode(''))
  body  = b'\r\n'.join(dataList)    
  payload= body
  headers = {
  'Authorization': 'Basic base64encoded < clientid:clientsecret > ',
  'Content-type': 'multipart/form-data; boundary={}'.format(boundary) 
  }
  conn.request("POST", "/wp-json/wp/v2/posts ", payload, headers)
  res= conn.getresponse()    
  data = res.read()    
  print (data.decode("utf-8"))   
  


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

  • Click on the Postman Samples tab in the plugin.
  • WordPress REST API Basic Authentication method postman implementation
  • Now, hover over the Basic Authentication Postman Samples card.
      • WordPress REST API Basic Authentication method postman JSON file for username : password
      • Import the downloaded JSON file into the Postman Application as shown below.
      • WordPress REST API Basic Authentication 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. Replace the <wp_base_url> with your Wordpress domain in the http://<wp_base_url>/wp-json/wp/v2/posts and replace the base64encoded <username:password> in the header with the base encoded value.
        • Example:
          For Username: testuser and password: password@123 the base64 encoded value will be ‘dGVzdHVzZXI6cGFzc3dvcmRAMTIz’

      WordPress REST API Authentication key method postman replace base url
      • WordPress REST API Basic Authentication method postman JSON file for client id and client secret
      • Import the downloaded JSON file into the Postman Application as shown below.
      • WordPress REST API Basic Authentication 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 base64encoded <clientid:clientsecret> in the header with the base encoded value.
      • WordPress REST API Basic Authentication method postman replace base url


1. Role-Based REST API restriction:


This feature restricts WordPress REST API access based on user roles. You can allowlist specific roles that are permitted to access certain REST API resources. When a REST API request is made, the user's role is checked, and access is granted only if the role is on the allowlist.


How to configure role-based REST API restriction in WordPress?

  • Go to the plugin Advanced Settings tab.
  • In the Role-Based Restriction section, all roles are allowed to access APIs by default.
  • Enable the checkbox next to the roles you want to restrict from accessing the APIs.
  • WordPress REST API Basic Authentication method postman implementation
  • In the above image, the subscriber role checkbox is enabled. So whenever an API request is made by the user, with his role as a 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, and OAuth 2.0 (Password grant).


2. Custom Header:


The Custom Header feature lets you use a custom header instead of the default 'Authorization' header. This adds an extra layer of security because the REST API will only accept requests with your defined custom header name. If someone tries to send a request using the default 'Authorization' header, access will be denied.


How to configure a custom header for WordPress REST API authentication?

  • Go to the plugin Advanced Settings tab.
  • In the Custom Header section, enter your preferred header name in the textbox.
  • Save changes to apply the new custom header for API requests.
  • WordPress REST API Basic Authentication method postman implementation

3. Exclude REST APIs:


The Exclude REST APIs feature lets you allow specific REST API endpoints to be accessed without authentication. These excluded APIs become publicly available, making them accessible without requiring a token or login.


How to configure excluded REST API in JWT authentication?

  • Go to the plugin Advanced Settings tab.
  • In the Exclude REST APIs section, enter your API endpoints in the required format.
  • The entered APIs will be excluded from authentication and available 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. Enable Advanced Encryption for the tokens using HMAC :


This feature is available in the Basic Authentication method. By default, tokens are encrypted using Base64 encoding, but with the advanced option, you can enable HMAC encryption for tokens. HMAC provides a much higher level of security, ensuring that API requests are strongly protected against tampering and unauthorized access.


How to configure HMAC encryption for tokens in WordPress Basic Authentication?

  • Go to the plugin Advanced Settings tab and open the Token Encryption Method section.
  • Select HMAC instead of Base64, then save changes to apply secure encryption for all tokens.


By default, Basic Authentication uses Base64 encoding, which is not fully secure. However, with plugins like ours, you can enable advanced HMAC encryption, making the tokens more secure and suitable for production use.

Basic Authentication is ideal for testing, development, or small-scale apps where simplicity is important. JWT is recommended for larger applications needing token-based sessions and scalability.

Yes. Basic Authentication can be used with user credentials or client credentials in mobile apps to securely validate API requests.

If disabled, your REST API endpoints will no longer validate requests with Basic Authentication. This may leave your API open to unauthorized access, so it's recommended to always keep authentication enabled.

With the Role-Based Restriction feature, you can specify which WordPress roles are allowed or denied access to your REST API endpoints.




Get Full-featured Trial



 Thank you for your response. We will get back to you soon.

Something went wrong. Please submit your query again

Integrate the External / Third-party REST API Endpoints

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.


ADFS_sso ×
Hello there!

Need Help? We are right here!

support