Search Results :

×

WordPress REST API Authentication Using Third Party Provider


WordPress REST API Authentication using Third Party Provider method involves the use of tokens (access-token/id-token/jwt token) received from third-party providers like Google, Facebook, Firebase, Apple, Azure AD, Keycloak, Okta, AWS Cognito, Github, Slack, Gitlab, etc. for accessing wordpress rest api securely.

WordPress endpoints are not secure by default and data can be stolen via REST APIs in JSON format. WordPress REST API Authentication allows you to call REST APIs with multiple security methods like Basic Auth, API KEY, JWT token, OAuth token . In this guide we will use OAuth token issued by OAuth/OpenID Connect/Firebase providers to validate the REST API requests which will keep your WordPress website protected and secure.
Each time a request to access the REST API will be made, the authentication will be done against that token issued by third-party providers like Google, Facebook, Firebase, Apple, okta, etc, and on the basis of the validation of the API token, the resources for that REST API request will be allowed to access. So, the single token you obtained on your app after SSO login can be used further for accessing WP REST API endpoints.


WordPress Rest API Authentication
By miniOrange

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

Know More

Pre-requisites : 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.

Usecase: Authenticate/protect WordPress REST API Endpoints using the JWT token obtained from Social Login/OAuth 2.0/OpenID Connect Identity providers(Server).

  • Suppose you have an android/ iOS mobile application and you have provided your user to login with multiple social login providers like Google, Facebook, Apple, Linkedin, Instagram or other OAuth/OpenID Connect providers like AWS Cognito, Auth0, Microsoft Azure, Okta, Keycloak, Firebase etc. and you want your users to access the WordPress REST API endpoints from the mobile applications, so you can perform authentication of the WordPress REST API endpoints access based on the access/id token (JWT token) obtained from the OAuth/OpenID Connect Identity providers(server) while single Sign On(SSO) for login into your application. So the access/id token/JWT is passed in the Authorization header of the API request with the token type as Bearer and validation of that token is done directly through the corresponding OAuth/OpenId Connect/Firebase Identity providers. So the validation request is made internally to the corresponding OAuth/OpenID Connect Server. If the validation of that token is successful, the REST API request will result in resource/data access, and on the validation failure, the error response will be returned. In this way, the resources/ data can be protected with the top level of security with authentication directly from OAuth/ OpenID Connect Identity providers.

  • WordPress REST API Authentication using third party key method
  • How this use case for the authentication can be achieved with our plugin:
    • 1. The WordPress REST API Endpoint request is made with the access/id token obtained from the OAuth/OpenID Connect Identity providers passed in the Authorization header with the token type as Bearer.

      2. The WordPress REST API request is monitored by our plugin and the JWT token validation/authentication request is sent to the OAuth/OpenID Connect Identity provider(Server).

      3. The response is returned from the OAuth/OpenID Connect Identity provider(Server) for the request being made earlier to validate the JWT token.

      4. If the JWT token validation/authentication is successful then the requested resource is allowed to be accessed which means the requestor is now authorized to access the resource/data and if in case, the token validation is failed then an error response will be returned. So the resource data is now protected and can be accessed on authorization, hence the security is not a concern.


    Related usecase: How to prevent WordPress REST API endpoints using the JWT token provided by Social Login or OAuth2.0/OpenID Connect Identity Providers?


    How to perform authentication and ensure security or perform authorization to grant access to the WordPress REST API endpoints on the basis of the access/id token provided by Social Login/OAuth providers during OAuth/OpenID SSO login flow?

Step 1: Setup WordPress REST API Authentication plugin

    • Select your Authentication method →Third party Provider and add Introspection Endpoint provided by your OAuth/OpenID Connect provider click on Save Configuration.
    • WordPress REST API Authentication using third party key method
    • Once you configure the plugin with the Introspection Endpoint provided by your provider, try to access your WordPress REST APIs using the access token/id_token provided by your OAuth Provider as shown below.
    • Request: GET https://<domain-name>/wp-json/wp/v2/posts
      Header: 
      access_token : < access_token >
      OR
      id_token  : < id_token  >
      
    • Check out the developer documentation for more details.

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", "< access_token > OR id_token <id_token>");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
 
OkHttpClient client  = new OkHttpClient().newBuilder().build();
MediaType mediaType  = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request  = new Request.Builder()
.url("http://<wp_base_url>/wp-json/wp/v2/posts ")
.method("GET", null)
 .addHeader = ("Authorization", "< access_token > OR id_token <id_token>")
 .build();
Response responseclient.newCall(request).execute();
        
 
var settings  = {
    "url": "http://<wp_base_url>/wp-json/wp/v2/posts ",
    "method": "GET",
    "timeout": 0,
    "headers": {
      "Authorization": "< access_token > OR id_token <id_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: < access_token > OR id_token <id_token>'
    
      ),
    
        ));          
      
$response = curl_exec($curl);
curl_close($curl);    
echo $response;
        
 
import http.client

conn   = http.client.HTTPSConnection("<wp_base_url>")
payload= "
headers = {
  'Authorization': '< access_token > OR id_token <id_token>'
}
conn.request("GET", "/wp-json/wp/v2/posts ", payload, headers)
res= conn.getresponse()    
data = res.read()    
print (data.decode("utf-8"))   

Postman Samples:

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

  • You can download the sample Postman request format from here.
  • Extract the downloaded zip file and import the extracted json file into the Postman application.
  • WordPress REST API Authentication using third party method postman implementation
  • Replace the < access_token > or < id_token > with the respective token provided by your OAuth 2.0 provider.
  • Example:
  • WordPress REST API Authentication using third party method postman replace url actual resource

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 ‘/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. Enable Advanced Encryption for the tokens using HMAC

    This feature is available with the Basic Authentication method in which by default the token is encrypted using Base64 encoding technique but with the advanced feature, the token can be encrypted with highly secure HMAC encryption which is very secure.

    WordPress REST API Basic Authentication method postman implementation

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

    7. Create User Specific API key/tokens

    • This feature is available within the API key method in which the tokens can be generated in accordance with the user information rather than a randomly generated token which is a universal key.
    • With the Universal API key/token, the user can not have permission to certain WordPress REST APIs with request method as POST,PUT,DELETE like creating users, posts, pages etc, in which a particular user permissions/role is required to perform operations via use of the REST API request as the universal key is randomly generated and does not contain the user based description.
    • So this User based API key/token feature allows the user to access the REST APIs with request method as POST,PUT,DELETE in WordPress which requires user credentials or certain roles to perform the operation such that the when the WordPress REST API request is made with the user-based key then the role of the user is obtained and he will be allowed to access the API only if he has permission to do so.
    • For Example: Only users with administrator and editor roles have permissions to create/edit/delete a post.
    • So, if a request is made to this API to create/delete/edit the post, the API response will result in “You are not allowed to perform this operation”.
    • Now, if a request is made with the user-based token generated for the user that has administrator or editor role then only they have access to this API and are able to perform the operation(create/update/delete) via the API call.
    • How to use this feature:

    • Select the user from the dropdown and click on the Create API Key button.
    • WordPress REST API Basic Authentication method postman implementation
    • A pop up will appear on the screen, you just need to click on the OK button to copy the token.
    • WordPress REST API Basic Authentication method postman implementation
    • Now this token can be used with the API request just like the universal key is used to make the API request.

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.

Recommended Plugins

WordPress REST API Authentication plugin provides the security for unauthorized access to your WordPress REST APIs. It provides you with a variety of authentication methods like Basic Authentication, API Key Authentication, OAuth 2.0 Authentication, JWT Authentication.

 Tested with 5.9.2

This plugin allows you to create custom endpoints/REST routes to fetch/modify/create/delete data with an easy-to-use graphical interface and with the custom SQL queries as well. Also, the plugin provides the feature to integrate external API into your WordPress site with third-party platforms.

 Tested with 5.9.2
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