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

Did an ASP.NET Core WebAPI HttpPost contain a JSON property?

Within my ASP.NET Core WebAPI Controller, I have a HttpPost method that receives the request body using the [FromBody] attribute. In this scenario, let's consider that I anticipate receiving the following JSON input, where null is an acceptable value ...

What is the best way to apply a class for styling my JavaScript code in CSS? I'm having trouble getting classList

I am having trouble adding a class to my JavaScript script in order to animate the images created in JavaScript to fall off the page. I have tried using the code element.classList.add("mystyle");, but every time I insert it, my JavaScript stops working. T ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Tooltip Bootstrap timing

I am currently working on creating a navigation bar with icon-only buttons that display tooltips when touched or tapped. Here is the code I have implemented: $('a[rel="tooltip"]').tooltip({ animated: 'fade', placement: ' ...

Tips for extracting tables from a document using Node.js

When converting an XML document to JSON using the xml-js library, one of the attributes includes HTML markup. After parsing, I end up with JSON that contains HTML within the "description":"_text": field. { "name": { ...

Unable to extract a singular data point from a Json dataset

Currently, I am working with a JSON response from the Telegram API and I am attempting to extract the value of the message into a string. Below is the JSON data: { "ok": true, "result": [ { "update_id": 855636291, ...

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

Getting information from MongoDB using Node.js and Angular

Currently, I am facing difficulty in retrieving data from MongoDB (I'm also using Mongoose) and sending it to Angular in order to populate the ng-repeat list with the retrieved data. I have managed to either display the data on a blank page directly f ...

The imported `theme` as `theme` was not visible in the file './theme'. The only possible export in the file is `default`

Encountering an error while attempting to export the theme from the index.js file. Below is the snippet of code present in the index.js file. import { createTheme } from "@mui/material"; import shadows from "./shadows"; import typograph ...

Tips for verifying that one of the two input fields is filled in Bootstrap 5 validation

I have implemented Bootstrap validation for the other input fields in this form by using the 'required' attribute. However, for these two specific fields, if at least one is not empty, then the form should be submitted. <form class="needs ...

The issue with the max-height transition not functioning properly arises when there are dynamic changes to the max-height

document.querySelectorAll('.sidebarCategory').forEach(el =>{ el.addEventListener('click', e =>{ let sub = el.nextElementSibling if(sub.style.maxHeight){ el.classList.remove('opened&apos ...

An error occurred while trying to insert JSON data into SQLite using Python

I am currently working on a project where I need to store raw JSON strings in a sqlite database using the sqlite3 module in Python. Here is what I have attempted: rows = [["a", "<json value>"]....["n", "<json_value>"]] cursor.executemany("""I ...

Encountering a 400 error (Bad Request)

I encountered a 400 Bad Request error while attempting to make a jQuery AJAX POST request to my WCF Service. Despite passing complex data to the WCF method, I am unable to receive the desired response. Interestingly, when I tested the same call using Post ...

Sharing sessions between WCF and ASP.NET

I am currently working on developing an infrastructure for a highly scalable application. My task involves creating a basic ASP.NET client page that interacts with a WCF service using an AJAX call (utilizing a simple xmlhttp object instead of the .net scri ...

Converting Repository Objects to Json in Symfony3

element, I am facing an issue while attempting to send a repository object as JSON. In my controller code, I have implemented a conditional check to ensure that the request is made via XmlHttpRequest. Upon receiving the data and fetching the corresponding ...

Ways to prevent other users from clicking or modifying a particular row

I have a data table in my project that will be accessed by multiple users simultaneously. My requirement is that once a row is selected and edited by one user, it should become unclickable for other users who are also viewing the same page or data table. ...

Finding the Right Path: Unraveling the Ember Way

Within my application, I have a requirement for the user to refrain from using the browser's back button once they reach the last page. To address this, I have implemented a method to update the existing url with the current page's url, thereby e ...

Adding a div via an Ajax call is only successful during the initial page load

Currently, I am utilizing a combination of YQL and jQuery to retrieve content from a distant page. While I am able to successfully load the content during the initial page load, I encounter an issue when attempting to return to the same page after navigati ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

Issue with Jquery .on() causing toggleClass function to not trigger

Adding a column dynamically to a table on click with JS/Jquery is achieved as demonstrated below $("#btn").click(function(){ $('#week_title').append('<th>Week '+count+'</th>'); count++; $('.tag&ap ...