Tips for securely implementing JSON web tokens when integrating an external application with the WordPress REST API

I have a query regarding JWT. Let's consider this situation.

  • A -> wordpress site with wp rest api enabled;
  • B -> External application (for example, a simple javascript/jQuery app)

Suppose I want to make a post request or create a new post on the wordpress website (A). I can do so by entering a username and password, then receiving a JWT token for authentication. If I set up a quick login feature, it would work without exposing the username and password. However, here lies the issue: What if I require the application to retrieve all the posts from A (wordpress website through rest api), but I don't want a login feature? Essentially, I need a method to input user login credentials to obtain a jwt token, but it seems illogical since someone could simply inspect the js code and extract that information?

Answer №1

In order to create a jwt, the code follows this format. It's important to note that the email and name are treated as one-time variables in the javascript file, while the username and email themselves aren't directly included in the code.

userSchema.methods.generateJwt = function() {
  var expiry = new Date();
  expiry.setDate(expiry.getDate() + 7);

  return jwt.sign(
    {
      _id: this._id,
      email: this.email,
      name: this.name,
      exp: parseInt(expiry.getTime() / 1000)
    },
    jwt_secret
  );
};

The only potential risk is accidentally revealing the jwt_secret. To prevent this, it's advised to store the secret securely within a dotenv file and avoid including it in version control.

require("dotenv").config();
const jwt_secret = process.env.JWT_SECRET;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sharing styles between ReactJS and Material-UI - best practices

I am currently facing an issue where I need to share styles across my entire web application. Here is the Problem: I have been using makeStyles in a repetitive manner as shown below: In component_A.js const useStyles = makeStyles({ specific_style: { ...

What causes the submit button to trigger an Ajax request?

There's something small that I need help with, and here it is. All of this is being done using jQuery. I have a function called "cont_refresh" that I use to refresh page content through an AJAX request to an external script for processing. In addit ...

What is the best way to organize my data so that it can be properly formatted and encoded as JSON?

I'm currently developing an application that requires using Google charts to display data from a MySql database. How can I properly structure my data and encode it into JSON format for this purpose? Here's the code I have so far: $con=mysql_con ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

lengthy conditional statement in JavaScript

Is there a more efficient way to handle a long series of if-else statements in JavaScript? I'm not experienced enough with the language to optimize this code. Any suggestions or guidance would be greatly appreciated. $('#webform-component-primar ...

Data is not appearing as expected in the React component when using the data

I'm currently facing an issue while working with MUI. I am able to retrieve the list in console.log, but nothing is being displayed on the screen - no errors or data, just the console.log output. Here is a snippet of the data that I am receiving: ...

An issue arose during the page prerendering process for "/" on Vercel | Next.js resulting in a deployment error

When attempting to deploy my website using Vercel and generating static pages, I encountered the following error in the logs: info - Generating static pages (0/6) Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/ ...

I'm trying to locate the ID of a widget already present in WordPress. This is necessary so I can trigger a specific function only when that widget is visible on the front end

Check out the hook that I'm currently utilizing: add_action('wp_footer', function (){ //Execute this code only if TablePress is active on the current page. if (is_active_widget(false, false, $this->id_base, true)){ add_action ...

The success function within the Ajax code is malfunctioning

I am currently utilizing express, node.js, and MySQL. The issue I am facing is that the success function inside my Ajax code is not working as expected. Below is the snippet of the Ajax code in question: function GetData_1(){ var state = $("#dpState_1"). ...

Struggling to run the CommandLineRunner in springboot. I am encountering issues with reading JSON data using the following code. Any suggestions on

Encountering an issue with Java version 11. The code seems error-free during compilation, but at runtime, the error "Failed to execute CommandLineRunner" is displayed. I have correctly added a JSON file to the resource directory, yet when trying to access ...

The headline box is displaying CSS code instead of the content. How can this issue be resolved?

Having an issue with a WordPress template that features a blue "headline" box that I need to change the color of to #333399. I tried inspecting the element, browsing through the code, and identified the code below as what needed modification: #headline, # ...

Facing issue with Codeigniter AJAX form where post data is not being collected

I am attempting to send a newsletter form to Codeigniter using AJAX. I have implemented CSRF protection, but I am facing issues with retrieving the posted values and receiving the response correctly. Here are the various scenarios: When I include name="e ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

What are the reasons for the failure of the AJAX call?

I have implemented this ajax function: function retrieveRelatedProperties(callback, error) { $.ajax({ url: '/LayerProperty/get', type: "GET", contentType: "application/json; charset=utf-8", dataType: "json", ...

Setting headers in Node.js after they have already been sent to the client is not allowed

I'm currently enrolled in a node.js course on Udemy which seems to be outdated. I've encountered some errors that I'm struggling to resolve. Here's what I've tried so far: using next(); adding return res inside all if statements ...

Employing ajax verification to ensure that the email address does not already exist prior to the main POST request (ASP.NET MVC4)

I used to have the ability to submit an asynchronous call to a method that checked for a username in the database and returned it as JSON while the user was typing. However, I can't seem to locate the tutorial that explained how to do this. Currently, ...

transform data into JSON format and transmit using jquery ajax

I have one object: var myobject = {first: 1, second: {test: 90}, third: [10, 20]}; and I need to convert it into a JSON string using jQuery ajax. Can someone please advise on how to achieve this? (I tried using JSON.stringify(), but it didn't work ...

The form data is being submitted multiple times by Ajax

Using jQuery and the Dialog widget, I have created a form that opens when the user clicks on a link. The form contains text fields and a file field for uploading files. When the user clicks on "Add File", Ajax uploads the file first and then makes a second ...

Parsley JS: A Solution for Distinct IDs

I have a form that contains multiple select boxes, and I need to ensure that no two select boxes have the same value selected. In simpler terms, if select box 1 is set to value 2 and select box 4 is also set to value 2, an error should be triggered. While ...

Activating gzip compression using fetch.js

I am utilizing fetch.js (https://github.com/github/fetch) to transmit a rather substantial JSON object to the backend. The size of the JSON is significant due to it containing an SVG image string. My question is whether fetch.js applies gzip compression a ...