Using Axios and Vue.js to Implement JWT Authorization (Header)

I am relatively new to the world of web development, so please forgive me if my question is not articulated clearly or if the solution seems obvious.

Essentially, I am looking to implement JWT authentication for my users using axios, vue.js, and JWT itself. My goal is to access a secure route:

router.post('/secureroute', checkAuth, (req, res) => {
res.status(200).json({
    message: 'all ok'
})
});

To achieve this, I have created a check-auth.js file:

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
 try {
    const token = req.headers.authorization.split(" ")[1];
    console.log(token);
    const decoded = jwt.verify(token, process.env.SECRET_KEY);
    next();
} catch (error) {
    return res.status(401).json({
        message: 'Auth failed'
    })
}

next();

}

A snippet from my Login.vue component:

methods: {
 login() {
  if (!this.username) this.alertUsername = true;
  if (!this.password) this.alertPassword = true;

  axios
    .post("/user/login", {
      username: this.username,
      password: this.password
    })
    .then(res => {
      localStorage.setItem("usertoken", res.data.token);
      if (res.data.token) {
        console.log("Success");
        router.push({ name: "start" });
      } else {
        this.alertWrong = true;
      }
      this.username = "";
      this.password = "";
    })
    .catch(err => {
      console.log(err);
    });
  this.emitMethod();
}

While testing with Postman and an authorization header, everything appears to be functioning correctly. However, despite numerous attempts and extensive research online, I am still unable to figure out how to successfully pass the JWT as an authorization header in my actual website project. I understand that it can be done with axios, but I am struggling to implement it in my specific case.

Answer №1

You've successfully set up your login flow and are now storing the user token in localStorage under the usertoken key. You’ve also ensured that your requests are properly processed when the authorization header is included.

An efficient way to handle API requests is to enhance axios for automatic inclusion of the authorization token and potentially preprocess the response received. This approach allows you to handle errors globally instead of individually and standardize request transformations.

To begin, create an abstraction function that invokes axios.request, utilizing a configuration object detailed here. Currently, focus on the headers property; however, additional enhancements can be made later.

export default function request (config) {
  const userToken = window.localStorage.getItem('usertoken');
  
  const requestConfig = { ...config };
  if (!requestConfig.headers) {
    requestConfig.headers = {};
  }

  if (userToken) {
    requestConfig.headers.authorization = `Bearer ${userToken}`;
  }

  return axios.request(requestConfig);
}

We can build upon this foundation:

export default function post (url, data = {}, config = {}) {
  return request({
    ...config,
    method: 'POST'
    url,
    data
  });
}

After implementing this modification, examining the developer console during request inspections reveals an additional header sent to the server provided the user token is correctly stored in localStorage.

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

Toggle class for a div upon clicking

I am attempting to add a class to a div element when it is clicked. Unfortunately, I'm having trouble getting it to work despite setting it up in the following manner: Javascript: function choose() { this.addClass("selected"); } HTML: <div ...

Looking to set up an event handler for the browser's back button in next.js?

When my modal opens, it adds a hash to the URL like example.com/#modal. I want to be able to recognize when the back button is clicked in the browser so I can toggle the state of the modal. The challenge is that since I am using next.js (server-side rend ...

React component not displaying passed props, although they are visible in the console.log output

When I render my code, a constant array const arr = [] is declared. Within the return statement, we have the following: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.m ...

Guide on comparing an object against an array and retrieving a specific output

If I were to create a data structure like this: const carObj = {"1234":"Corvette","4321":"Subaru","8891":"Volvo"}; And also have an array that contains the IDs: const myArray = [1234, 4321, 8891, ...

The type x cannot be assigned to the parameter '{ x: any; }'

Currently learning Angular and Typescript but encountering an error. It seems to be related to specifying the type, but I'm unsure of the exact issue. Still new at this, so any guidance is appreciated! src/app/shopping-list-new/shopping-edit/shopp ...

A step-by-step guide on using Javascript to transform images into text

Hey there! I'm looking for some help to convert an image into text. The idea is that when someone uploads an image and hits the "Submit" button, the text from the image should display in a textarea below. However, the code I've been working on do ...

The performance problem of calling a method in a Vue 2 v-for loop

Can someone help me understand why my code is calling someFunction() four times instead of just once? This is the structure: <div id="app"> <div v-for="item in items" :key="item.id"> <input v-model=" ...

Guide to implementing a DataTable in MVC4 UI using jQuery

Looking to set up a DataTable using jQuery similar to the one shown in this image: https://i.stack.imgur.com/DNUcd.png I'm not very comfortable with jQuery, so please be patient and avoid asking me what I've tried. I don't know how to stru ...

The Discord.js Avatar command does not support mentioning users

Everything seems to be working fine when I check my own avatar, but it doesn't work properly when I mention another user. Here's the code I'm using: client.on('message', message => { if (message.content === `${prefix}ava`) { ...

Clear the previously displayed scene in Three.js

After setting up a renderer scene in threejs, I encountered an issue when trying to load a model for the second time. I'm looking for a way to clear the previous rendered scene from the canvas. Is there a solution available within threejs? ...

Using Jquery to sequentially add a class to individual <li> elements in a list, with a delay of 5 seconds for each addition

Currently, I am working on a website that requires me to assign a class of 'active' to a series of <li> elements. The number of <li> elements varies - sometimes there are six, other times 17. This needs to be adaptable and dynamic. ...

Create a web component build using vue-cli 3 that includes the vue dependency bundled together

Currently, I am utilizing vue-cli 3 to bundle my vue components into web components with a command that looks like this: package.json "build:wc": "vue-cli-service build --target wc-async --name webcomponent-global 'src/components/*/*.vue'" Eve ...

Issue encountered while utilizing Mongoose ArrayFilters for updating a nested subdocument

I am working with a Mongoose collection and need to update a nested subdocument within it. Here is the basic structure: The collection has a parent entry (Map) This entry contains an array of children (Phases) Each child has one or more grandchildren (S ...

"Create a HTML Form with a Submit Button that Does Not Refresh the Page

I created a form with fields for Name and Email, along with a submit button. The submit button is set to trigger the invite() JavaScript method upon being clicked. <form id="inviteForm" action=""> <div class="modal-body"> ...

Counting the "Children Count" of a parent element in a collapsible tree diagram using D3

I have been working on creating a collapsible tree chart using D3 js, and I have managed to meet some of the requirements. However, I am looking to add the functionality of displaying the number of children for each parent node. Here is an example: Click ...

Creating user groups with MongoDB and Node.js

Recently I started working with MongoDB and I'm looking to implement a feature using mongoose and nodejs. Specifically, I want to group participants based on the room description. Here is the schema: //schema for rooms.js //ROOMS const schema = mon ...

Embed Vue component within data section

I am attempting to create a custom tooltip for apexcharts similar to the example shown here: tooltip: { custom: function({series, seriesIndex, dataPointIndex, w}) { return '<div class="arrow_box">' + '<span> ...

Tips on how to connect a single reducer function to trigger another dispatch action

In my React project, I'm utilizing a Redux-Toolkit (RTK) state slice that is being persisted with localStorage through the use of the redux-persist library. This is a simplified version of how it looks: const initLocations = [] const locationsPersist ...

Guide to displaying dashboard components within the same page

I have a Dashboard Component with a side nav that contains menu items such as Dashboard, Manage Companies, ContactUs, and Manage Users. When clicking on Dashboard, I want to render the dashboard component on the same page. Similarly, when clicking on Manag ...

Displaying the second image twice in a jQuery image slider

When attempting to implement a slider on my website, I encountered an issue where the second image appears twice in a row before the slider starts working as expected. I'm struggling to figure out why this is happening. Here is the jQuery code I am u ...