Search Results :

×

Guide to Secure WordPress REST APIs with Basic Authentication


WordPress Basic Authentication for REST APIs provides a way to secure access to your WordPress endpoints. It involves validating API requests using a token generated from a username and password or client credentials. This authentication method verifies your identity when interacting with the web service, ensuring that only authorized users can access the API.


How to Implement Basic Auth plugin in WordPress to secure REST APIs

When working with the WordPress REST API, you might need to use Basic Authentication to securely interact with your site. Basic Auth is a simple authentication scheme built into the HTTP protocol. It involves sending credentials (username/email and password) encoded in base64 with each request.



WordPress Rest API Authentication
By miniOrange

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

Know More

Setting Up Basic Authentication for WP API

To get started with WP API Basic Auth, you’ll need to install a WordPress REST API Authentication plugin. This plugin allows the REST API to accept Basic Authentication credentials. Here’s a step-by-step guide:


  • Install WordPress REST API Authentication Plugin: Search for and install WordPress REST API Authentication plugin by miniOrange from the WordPress plugin repository. This plugin will enable the REST API Basic Authentication on your site.
  • Activate the Plugin: After installation, activate the plugin from your WordPress dashboard. .
  • Configure Authentication: Follow the steps below to configure Basic Authentication



Use Case: Enhancing Security of WordPress REST API Endpoints with Basic Authentication


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 is crucial.

Here’s 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 in to your app, a session is created. 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 will determine the actions they are allowed to perform and the content they can access. This allows you to control user capabilities and maintain secure interactions with your WordPress site.

By using WordPress Basic Authentication with user credentials, you can 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 credentials. If the 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

Setup REST API Basic Authentication Method


miniorange img 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
  • After you save the REST API Basic Auth Configuration with Username and Password, 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 <username:password>
    Sample Request Format- Example => username : testuser and password : password@123

    
           Sample curl Request Format-
           curl -H "Authorization:Basic base64encoded <username:password>"
           -X POST http://<wp_base_url>/wp-json/wp/v2/posts -d "title=sample post&status=publish" 
       
  • PHP base64_encode(string) function for base64 encoding can be used as follows:
  •   
      base64_encode(‘testuser:password@123’) will results into ‘eGw2UllOdFN6WmxKOlNMRWcwS1ZYdFVrbm5XbVV2cG9RV FNLZw==’ 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 UserName & Password.

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.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"))   
   

miniorange img Postman Samples:

    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.
    • a) For Username-Password

        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

      b) For Client ID and Client Secret

      • 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

miniorange img Feature Description

    1. Role-Based REST API restriction:

    This feature allows you to restrict REST API access in accordance with user roles. You have the option to specify the roles that are permitted to access the requested resource through REST APIs. Consequently, when a user makes a REST API request, their role is checked, and access to the resource is granted exclusively if their role is included in the whitelist.


    How to configure it?

    • First, go to the plugin ‘Advanced Settings’ tab.
    • Then, in the Role based Restriction section, all the roles by default will be allowed to access the APIs. You can enable the checkbox of the roles for which you want to restrict access.
    • 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:

    This feature offers the ability to select a personalized header instead of the default 'Authorization' header. This enhances security by allowing you to name the header as per your custom preference. Consequently, if someone attempts to make a REST API request with a header named 'Authorization,' they will be allowed 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 designate certain REST APIs as whitelisted, permitting them to be accessed directly without the need for authentication. Consequently, all these whitelisted REST APIs 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. Enable Advanced Encryption for the tokens using HMAC :

    This feature is offered within the Basic Authentication method, where the token is typically encrypted using Base64 encoding by default. However, with the advanced option, the token can be encrypted using the highly secure HMAC encryption method, which ensures a very high level of security.


    WordPress REST API Basic Authentication method using user credentials

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