Search Results :

×

WordPress REST API JWT Authentication Method


This method of WordPress REST API endpoints authentication involves the REST APIs access on validation based on the JWT(JSON Web Token), Each time a request to access the WordPress REST API endpoint will be made, the authentication will be done against that JWT token, and on the basis of the verification of that JWT token, the resources for that API request will be allowed to access. The JWT token is generated based on WordPress user credentials and is highly encrypted, hence security is not compromised.




WordPress Rest API Authentication
By miniOrange

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

Know More

Download And Installation

  • 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.

idp_sso_image1 Use Case: Secure/Protect or authentication of WordPress REST API Endpoints using the JWT (JSON Web Token).

  • Suppose you have a mobile/web application and want to allow access to the WordPress REST API endpoints based on the user capabilities such that only users with that particular capability should perform create/update operations while users with other roles can only view that. Then in such cases, you can authenticate the REST API endpoints using the JWT(JSON Web Tokens) obtained in accordance with user credentials and WordPress JWT authentication allows you to do it very securely. So, making the REST API request with this JWT passed in the Authorization header allows access to the resource/data or provides the capability/authorization to perform WordPress operation that requires particular user capability. JWT Authentication for WordPress REST API provides the encryption of the token using 2 methods- HSA or RSA and is valid for a limited time. Hence security is not a concern.


    The JWT token generated for the JWT authentication consists of WordPress user information and hence this token can be decoded using the valid secret key/public certificate on another application to create a user there or sync updated user information. The JWT token is also a time based token meaning it expires after a certain period of time which can be set as per the requirements and hence after its expiration, the APIs will not be allowed to access and neither the user information can be decoded which makes JWT Authentication for WordPress REST API a secured authentication method.


  • The flow for WordPress REST API authentication can be achieved using the JWT method is explained below:
  • WordPress REST API JWT Authentication method using jwt

      1. The WordPress REST API request is made with all the required parameters to obtain the JWT token. The obtained JWT token is provided in encrypted format using the HSA or RSA algorithm hence there will be utmost security.

      2. Then the actual WordPress REST API request to access the resource/data or to perform operations with the WordPress database is made with the JWT token obtained in the last step is passed in the Authorization header with the token types as Bearer and our plugin will validate that JWT token and if the validation or authentication is successful then the API requester will be provided with the resource else an error response will be returned. So our plugin will act both as the JWT token provider and the JWT token validator.


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

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


Setup REST API JWT Authentication Method


  • 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

  • Here you would need to make two API calls:

I : Get the JWT Token

  • 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.

II : Send API Request

  • 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.

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

    idp_sso_image1 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 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.
    • REST API Request to obtain the JWT token
      • 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.
    • REST API Request to obtain the actual resource
      • 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

    idp_sso_image1 Feature Description

      1. Role Based REST API restriction:

      This feature allows restricting the REST API access based on the user roles. You can whitelist the roles for which you want to allow access to the requested resource for the REST APIs. So whenever a REST API request is made by a user, his role will be fetched and only allowed to access the resource if his role is whitelisted.


      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 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

      This feature provides an option to choose a custom header rather than the default ‘Authorization’ header.

      It will increase the security as you have the header named with your ‘custom name’, so if someone makes the REST API request with a header as ‘Authorization’ then he won’t be able 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 whitelist your REST APIs so these can be accessed directly without any authentication. Hence all these whitelisted REST APIs are publicly available.


      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 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

      This feature is applicable for JWT and OAuth 2.0 methods which uses time based tokens to authenticate the WordPress REST API endpoints. This feature allows you to set the custom expiry for the tokens such that the token will no longer be valid once the token expires.


      How to configure it?

      • First, go to the plugin ‘Advanced Settings’ tab.
      • Then in the ‘Token Expiry Configuration’ section, the access token validity and refresh token(used for OAuth 2.0 method) can be altered. By default the access token expiry time is set to 60 minutes and the refresh token expiry time is set to 14 days. Hence with this feature, the expiry can be adjusted accordingly as per the requirements.
      • WordPress REST API Basic Authentication method postman implementation

      Hence, with this custom token expiry feature, the security is increased furthermore.

      5. Signature Validation for JWT based tokens

      This feature allows a secure signing of the JWT signature for the JWT token such that your JWT token is much more secure and the signature can only be decoded using the client secret/certificate. It means your signature is private and can not be seen by others.

      WordPress REST API Basic Authentication method postman implementation

      We provide the support for 2 Signing algorithms: HS256 and RS256.So, any of the signing algorithms can be chosen from the dropdown as shown in the above image.

      Also, you need to add your client secret or certificate from which is used to sign the signature of the JWT.

      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