Search Results :

×

JWT Authentication for WP REST API

JWT authentication for WP REST API is a simple way to keep WordPress REST API endpoints secure and protected. Instead of sending usernames and passwords every time, WordPress JWT authentication uses a secure token to check who is making the request. This helps make sure that only approved users or apps can access protected REST API endpoints. The JWT token is generated using WordPress user credentials and is highly encrypted, which ensures strong security without compromising access.



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   

What is WordPress JWT Authentication?

JWT authentication for WP REST API is a simple way to keep WordPress REST API endpoints secure and protected. Instead of sending usernames and passwords every time, WordPress JWT authentication uses a secure token to check who is making the request. This helps make sure that only approved users or apps can access protected REST API endpoints. The JWT token is generated using WordPress user credentials and is highly encrypted, which ensures strong security without compromising access.

  • Log in to your WordPress site as an admin.
  • From the WordPress Dashboard, go to Plugins, click on Add New.
  • Search for a REST API Authentication for WP.
  • Click Install Now to add the plugin to your site.
  • After installation, click on Activate to start using the plugin.


If you are developing a mobile or web application and need controlled access to WordPress REST APIs, JWT Authentication for WP REST APIs offers a secure solution. With WordPress JWT Authentication, you can define access levels so users with specific capabilities can create or update content, while others are limited to viewing data only.

  • Using JWT token based authentication, REST API endpoints are protected by WP JWT access tokens generated from valid WordPress user credentials. By including the JWT token in the Authorization header, your application can safely access protected resources or perform role-based actions using JWT Authentication for WP REST APIs.
  • These tokens are secured using encryption algorithms such as HSA or RSA and automatically expire after a defined period, strengthening overall security. Each token contains WordPress user information that can be decoded using a secret key or certificate, making wordpress JWT authentication ideal for syncing users or creating accounts across multiple systems.
  • WP JWT Refresh Tokens allow users to renew their sessions securely without the need to log in again. Overall, JWT token based authentication combined with WordPress JWT authentication ensures secure API access while enabling seamless and efficient communication between your application and WordPress.

  • Secure WordPress REST APIs with JWT Authentication
  • WordPress REST API JWT Authentication method using jwt

    1. WordPress REST API request is initiated with the required credentials and parameters to generate a JWT token using WordPress JWT authentication. The issued token is secured through JWT token based authentication and encrypted using industry-standard algorithms such as HS256 or RSA to ensure strong data protection.

    2. For subsequent requests, the WordPress REST API call to fetch data or perform actions includes the JWT token in the Authorization header as a Bearer token. With JWT authentication for WP REST API, the plugin validates the token before processing the request. If the token is valid, access to the requested resource is granted; if not, an error response is returned. In this process, WordPress JWT authentication plugin handles both the creation and verification of tokens, ensuring every API request remains 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).


JWT ensures security by using JWT token based authentication to verify every request without repeatedly sending usernames and passwords. In JWT authentication for WP REST API, the token is digitally signed (HS256) or signed with a private key (RSA), so it can’t be altered without detection. Tokens also expire after a set time, which limits risk if a token is ever exposed. This makes wordpress JWT authentication a secure way to protect WordPress REST API endpoints.

You have to add the token in the request headers using the Authorization header as a Bearer token. This is the standard approach in JWT authentication for WP REST APIs and is core to jwt token based authentication. for example:
Authorization: Bearer YOUR_JWT_TOKEN

When the access token expires, the API will return an authorization error (typically 401). With WordPress JWT authentication, you can use a refresh token (WP JWT refresh token) to request a new access token without logging in again. This flow is a key benefit of JWT token based authentication, keeping sessions secure and user-friendly in JWT authentication for WP REST APIs.

Yes. The plugin supports both token signing using HS256 and RSA, depending on configuration. HS256 uses a shared secret, while RSA uses a public/private key pair. This flexibility strengthens JWT token based authentication and fits different security requirements for JWT authentication for WP REST API.

You can test WordPress JWT authentication in a simple two-step flow:

  • Generate a token : Use the plugin’s token endpoint with valid WordPress credentials and confirm you receive a JWT. curl -d" username=&password=" -X POST http:///wp-json/api/v1/token
  • Call a protected REST API endpoint: Send a request to a protected endpoint with:-
    Authorization: Bearer YOUR_JWT_TOKEN




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