Search Results :

×

WordPress REST API JWT Authentication Method

WordPress REST API endpoint authentication uses JWT (JSON Web Token) to validate requests securely. Each time a request is made to access a WordPress REST API endpoint, the system checks the JWT token. If the token is verified, the requested resources are granted. The JWT token is generated using WordPress user credentials and is highly encrypted, ensuring strong security without compromising access. This approach makes it easier to manage secure communication between applications and the WordPress REST API.



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   

  • Log into your WordPress instance 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.


  • If you have a mobile or web application and need to control access to WordPress REST API endpoints based on user capabilities, JWT authentication provides a secure solution.

  • For example, users with specific capabilities can perform create or update operations, while other roles may only be able to view data. In such cases, the REST API endpoints can be authenticated using JWT (JSON Web Tokens) generated with valid user credentials.

  • By passing this JWT in the Authorization header, requests can securely access resources or perform WordPress operations requiring certain capabilities.

  • JWT Authentication for WordPress REST API uses encryption methods such as HSA or RSA, and tokens remain valid for a limited time, ensuring strong protection without compromising security.

  • The JWT token generated for JWT authentication contains WordPress user information, which allows it to be decoded with a valid secret key or public certificate on another application. This makes it possible to create a user or sync updated user information across systems. Since the JWT token is time-based, it expires after a set duration defined by the requirements. Once expired, the APIs cannot be accessed, and the user information cannot be decoded. This ensures that JWT Authentication for WordPress REST API remains a secure authentication method, protecting both data and access.


  • Secure WordPress REST API authentication using the JWT method is outlined below
  • WordPress REST API JWT Authentication method using jwt

    1. A WordPress REST API request is made with the required parameters to obtain a JWT token. The generated token is encrypted using the HS256 or RSA algorithm, ensuring strong security.

    2. The WordPress REST API request to access data or perform operations is sent with the JWT token in the Authorization header as a Bearer token. The plugin first checks (validates) the token. If it is valid, access to the resource is granted; if not, an error response is returned. In this way, the plugin both creates the JWT token and later verifies the token to make sure every request is secure.



Related Usecase:

  • How to make JWT authenticated requests to the WordPress REST API endpoints?
  • Authentication of Woocommerce/WordPress REST APIs using JWT (JSON Web Token).



  • In the plugin, go to the Configure Methods tab in the left section.
  • Click on JWT Authentication as the API Authentication method.
  • WordPress REST API jwt Authentication method
  • Select the Token Generation type . By default, the HS256 algorithm and randomly generated unique secret key are used respectively and click Next in the top right corner.
  • In order to test the functionality, Fill in the Username and Password fields for an existing user.
  • WordPress REST API jwt Authentication method
  • Click on Fetch Token . A JWT token (jwt_token) will be displayed in response whose value you can copy to the clipboard for making a GET request.
  • Paste the JWT token obtained from Step 6.
  • Click Test Configuration and the response will be displayed on the screen.
  • Click the Finish button.
  • WordPress REST API jwt Authentication method
  • In the plugin, go to Configure API Authentication tab and click on JWT Authentication as the API Authentication method.
  • Select the Signing Algorithm and Client Secret. By default, HS256 algorithm and randomly genefrated secret key is used respectively.
  • Finally, click on Save Configuration so JWT Authentication for WordPress REST API Authentication will be enabled.
  • WordPress REST API JWT Authentication method using jwt
  • Here you would need to make two API calls:

  • To get the JWT Token, you would need to make an REST API Call to Token endpoint as below:
  • Request:POST https://<domain-name>/wp-json/api/v1/token
      Body:username = <wordpress username>
      password = <wordpress password>
    
      Sample curl Request Format-
      curl -d "username=<wordpress_username>&password=<wordpress_password>"
      -X POST http://<wp_base_url>/wp-json/api/v1/token
      

    This API endpoints is also called as user authentication API or WordPress login API endpoint such that if we make a request to this endpoint with the WordPress user credentials and if credentials are valid, the successful response will return containing JWT token, else the error response will be shown accordingly.

  • Check out the Error Response for getting JWT token.
  • Once you get the JWT token, you can use it to request access to the WordPress REST APIs as shown below:
  • Request: GET  https://<domain-name>/wp-json/wp/v2/posts
      Header: Authorization : Bearer <JWT token>
    
      Sample curl Request Format-
      curl -H "Authorization:Bearer <jwt_token >"
      -X GET http://<wp_base_url>/wp-json/wp/v2/posts
      
  • NOTE: Above token is valid for 1 hour by default and it can be customised as well. Once token is expired it can be generated again.
  • Check out the developer documentation for more details.
  • Check out the Error Response for making API with JWT token.

Congratulations! You have successfully configured JWT Authentication method for REST API calls using miniOrange WordPress REST API Authentication method.


 
  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 < jwt_token >");    
  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 < jwt_token >")    
   .build();
  Response response= client.newCall(request).execute();
          
 
  var settings  = {
      "url": "http://<wp_base_url>/wp-json/wp/v2/posts ",
      "method": "GET",
      "timeout": 0,
      "headers": {
          "Authorization": "Bearer < jwt_token >"
        },        
    };
    
    $.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 => 'GET',
          CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer < jwt_token >'
          ),
          ));          
        
  $response = curl_exec($curl);
  curl_close($curl);    
  echo $response;
          
 
  import http.client
  
  conn = http.client.HTTPSConnection("<wp_base_url>")
  payload= "
  headers = {
      'Authorization': 'Bearer < jwt_token >'
  }
  conn.request("GET", "/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/api/v1/token ");
  client.Timeout = -1;
  var request = new RestRequest(Method.POST);
  request.AlwaysMultipartFormData = true;
  request.AddParameter("username", "<wordpress_username>");    
  request.AddParameter("password", "<wordpress_password>");    
  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", "<wordpress_username>"); 
  .addFormDataPart("password", "<wordpress_password>"); 
  .build();
  Request request  = new Request.Builder()
  .url("http://<wp_base_url>/wp-json/api/v1/token ")
  .method("POST", body)
   .build();
  Response responseclient.newCall(request).execute();
        
 
  var form = new FormData();
  form.append("username", "<wordpress_username>");
  form.append("password", "<wordpress_password>");  
  
  var settings  = {
      "url": "http://<wp_base_url>/wp-json/api/v1/token ",
      "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/api/v1/token%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('username' => '<wordpress_username>','password' => '<wordpress_password>'),
          ));
          
  $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("<wordpress_username>"))    
  
  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("<wordpress_password>"))    
  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/api/v1/token", 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 JWT Authentication method postman implementation
  • A JSON file will be auto downloaded.
  • WordPress REST API JWT Authentication method postman JSON file
  • Import the downloaded JSON file into the Postman Application as shown below.
    • 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 <wordpress_username> with WordPress username and <wordpress_username> with WordPress password in the body parameters.
    • WordPress REST JWT Authentication method postman replace base url
    • Example
    • WordPress REST JWT Authentication method postman replace base url example
    • NOTE: Copy the jwt token obtained from response. It will be used in the resource API requests to authenticate.
    • 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 <jwt_token> with the jwt token copied from the response obtained after the token request.
    • WordPress REST JWT Authentication method postman replace base url actual resource
    • Example
    • WordPress REST API JWT Authentication method postman replace url actual resource

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 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, 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 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 if you want to exclude the REST API ‘ '<your domain> /wp-json/wp/v2/posts’ then you have to enter ‘/wp/v2/posts’ in the textbox.

4. Custom Token Expiry:


The Custom Token Expiry feature works with JWT and OAuth 2.0 authentication methods, allowing you to set custom expiration times for tokens used to access WordPress REST API endpoints. Once the configured time is reached, the token automatically becomes invalid, enhancing security and giving you control over access duration.

How to set custom token expiry in JWT authentication?

  • Go to the plugin Advanced Settings tab.
  • Open the Token Expiry Configuration section.
  • Adjust the Access Token expiry time (default: 60 minutes).
  • (For OAuth 2.0) Adjust the Refresh Token expiry time (default: 14 days).
  • Save changes to apply your custom token expiry settings.
  • WordPress REST API Basic Authentication method postman implementation

5. Signature Validation for JWT-based tokens:


The Signature Validation feature securely signs JWT tokens to protect WordPress REST API authentication. Each token signature can only be validated using the client secret or certificate, ensuring that the signature remains private and secure and cannot be accessed or modified by unauthorized users.

WordPress REST API Basic Authentication method postman implementation

How to configure JWT signature validation using HS256 or RS256?

The plugin supports two signing algorithms for JWT tokens: HS256 and RS256. You can select either algorithm from the dropdown menu. To complete signature validation, add your client secret or certificate, which is used to securely sign the JWT signature and ensure token authenticity.

6. Refresh Token


Refresh token is a long-lived token used to obtain a new access token without requiring the user to log in again. This feature is crucial for maintaining a user's session when the access token expires. Access tokens typically have a short lifespan (like 15 minutes to 1 hour) for security reasons, but refresh tokens are designed to last longer (days, weeks, or even months).

7. Revoke Token


Revoking a token means invalidating it before its expiration. This feature is crucial for security, especially in cases like:

  • A user logs out of their session.
  • A user changes their password.
  • A token is compromised (stolen or leaked).
  • Admins want to force a logout or invalidate tokens for certain users (e.g., after a security breach).


The JWT token is generated using WordPress user credentials and encrypted using either the HSA (HS256) or RSA algorithm. It is valid only for a limited time, which you can customize. This time-based expiration ensures that once the token expires, API access is revoked and the token can't be decoded—making this a secure authentication method.

The JWT token must be included in the Authorization header of your WordPress REST API request. The token type should be specified as Bearer, for example: Authorization: Bearer <your_jwt_token>. This ensures the plugin can validate the request before granting access.

Since the JWT token is time-based, it expires after a set duration defined in the configuration. Once expired, the token cannot be used to access API resources. To refresh, you must request a new JWT token using the user's credentials. This ensures security and prevents unauthorized long-term access.

Yes. The plugin allows JWT token generation using either the HS256 algorithm with a secret key or the RSA algorithm with a public/private key pair. By default, the HS256 method is selected with a randomly generated secret key, but you can configure it as per your security requirements.

The plugin provides a built-in testing option. You can enter a valid username and password for an existing WordPress user to generate a JWT token. Once generated, use the token to make a GET request within the plugin interface or through tools like Postman to confirm successful authentication.




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