Streamline user access with automatic JWT authentication in Vue application

When it comes to authorizing actions and accessing protected resources from my backend, I rely on jwt tokens for security. Here is an overview of the technologies used in both the frontend and backend:

Frontend: Vue, Vue Router, VueX, Vuetify

Backend: Express, jwt tokens, cookieParser

After successfully calling the login route, the frontend receives an accessToken along with user data such as username, email, and userId. In addition, a httpOnly cookie containing the refreshToken is sent back and stored in the database. The vuex store is then updated to reflect the user's logged-in status and information, while also saving the user object to localStorage.

To ensure seamless auto-login functionality when reopening tabs or windows, the vuex store is initiated with user data retrieved from the localStorage at the beginning.

// read out localStorage for the user
const user = JSON.parse(localStorage.getItem('user'));

const initialState = user
    ? { user, loggedIn: true, accessToken: null }
    : { user: null, loggedIn: false, accessToken: null };

Prior to accessing any protected routes, the vue router's beforeEach method is utilized to check if the vuex getter auth/getUser returns a valid user object. If not, the router redirects to the login page for re-authorization.

const routes = [
  { path: '/login', name: 'Login', component: Login, meta: { authRequired: false }},
  { path: '/home', name: 'Home', component: Home, meta: { authRequired: true }}
]

const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes });

router.beforeEach(async (to, from, next) => {
  if (to.meta.authRequired) {
    let user = VuexStore.getters['auth/getUser'];
    if (!user) {
      next({ path: '/login'});
    }
  }
  next();
});

There is a concern about the validity of the user object stored in the localStorage and whether relying solely on that for auto-login is secure enough. Should the received accessToken or the cookie with the refreshToken be used in some way for the auto-login process instead? Your insights are appreciated. Thanks!

Answer №1

Hey, you're almost at the finish line! What you need is a refresh token:

https://example.com/blog/refresh-tokens-explained

The key is to monitor when the current token expires in your localStorage and then automatically refresh it before expiration to prevent the user from being logged out.

Adding on:

But how can we ensure that the user object in the localStorage is legitimate and not just set to true? Should we rely on the received accessToken or utilize the cookie with the refreshToken for automatic login? Thanks for any insights.

Your API takes care of that. If the user attempts to access your API with an invalid access token, the API will reject it and trigger an error. So even if a user manipulates client-side data, the server remains the ultimate authority ;-)

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

Exploring the MEVN Stack's Integration with Image Uploading

After successfully implementing an image upload system on my website, I encountered difficulty in linking to the uploaded images. The root directory of my project includes a client folder for vuejs app and a server folder for backend logic. When users upl ...

The issue of updating a dynamic title within a for loop using Vue remains unresolved

I am trying to display an array of objects with titles for each month in a sequential order. However, not every object in the loop will have a title displayed - it should only show the title if there is a change in the month between objects. For example, ...

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

Closing the Bootstrap navbar collapse by clicking anywhere outside of the menu area

Excuse my lack of experience, but I have a question. I am trying to make Bootstrap "navbar-collapse" close when clicking away or on one of the list items. I stumbled upon this code that seems to do the trick. $(document).on('click',function() { ...

I'm having trouble with my Laravel edit page not functioning properly when using vue.js. Can anyone help me troubleshoot

Currently, I am developing a dashboard to display details. Users can click on the edit button to modify their information. However, when I try to edit by clicking the button, nothing happens. It seems like the editing feature is not functioning properly, a ...

Utilizing the reduce() function to simultaneously assign values to two variables from data input

Looking to simplify the following function using reduce(), as the operations for variables selectedEnrolled and selectedNotEnrolled are quite similar. I attempted to use map(), but since I wasn't returning anything, it led to unintended side effects ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

Create a regulation that permits access solely to individuals currently logged into the system database

I am a beginner when it comes to working with Firebase and its rules. My goal is to implement a system where each user in the Firestore database has a boolean field called isOnline, as shown in the image I have attached. https://i.stack.imgur.com/7M3dc.pn ...

express.js does not properly support the app.get functionality

app.get('/:id', function (req, res){ UserModel.find({ user: req.params.id}, function (err, user){ if (err) throw err; console.log(user + '\n\n'); res.render('profile.ejs', { ...

Tips for maintaining the original URL when updating the displayed page within ExpressJS

One common method for displaying a different page is to call a url /this from the HTML, which is then captured by app.get('/this'... and used to render the new page. To ensure the URL remains unchanged, I use '' to trigger the renderin ...

Encountering the "node:internal/modules/cjs/loader:1050" error while attempting to execute a folder using the "npm run dev" command

I am encountering an issue while attempting to execute a folder using npm run dev, consistently resulting in the same error message. PS C:\Users\My Name\Desktop\My Folder> npm run dev Debugger attached. > <a href="/cdn-cgi/l/e ...

Can jQuery effortlessly glide downward, come to a stop, continue downward, and then move upwards?

My webpage features a large table created and populated automatically every minute using ajax. The code structure is as follows: $(document).ready(function(){ setInterval(function(){ $.ajax({ //code to call backend, get the data, ...

What is the best method to display an asterisk (*) in red while using React and Material UI

In my form, I want to indicate required fields with a red star (*). Is there a way to display the star in red color? Also, why does the border turn blue when I click on an input field? Here is the code and screenshot for reference: https://codesandbox.io/ ...

Various concatenated and compressed JavaScript files across multiple HTML documents within a single application

In my express.js application, I have different routes such as /home and /dashboard. For example, on the home page, I include: jquery.js, underscore.js, somemodule1.js, somemodule2.js. On the dashboard, I include: jquery.js, underscore.js, somemodule3.js, ...

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

How can Vue i18n be utilized as a JavaScript object instead of within the template?

Can vue and vue-i18n be utilized solely with JavaScript (as an object) instead of in the template? Is it feasible to implement it in a scenario similar to window.confirm? Appreciate your assistance. ...

React to the MFA_Setup challenge with a cutting-edge application using Node/express, AWS-sdk

My front-end uses a React app while my back-end utilizes Node/Express. For all Cognito users in my application, Multi-Factor Authentication (MFA) is mandatory. The normal login flow in my application (without MFA) is as follows: Cognito user enters thei ...

Receiving a NaN output rather than a numerical value

Experiencing what seems to be a straightforward syntax error, but I'm unable to pinpoint it. Controller: $scope.startCounter = 3; $scope.startTimeouter = function (number) { $scope.startCounter = number - 1; mytimeouter = $t ...

Vue.js parent component sending new data: prop mutation detected

Encountering an issue in the console with the following error message: Instead, use a data or computed property based on the prop's value. Prop being mutated: "sortType" Within my root file, I have an API and filter function sending data to comp ...

AngularJS view does not wait for the completion of $http.get request

Within my controller, the code snippet below is present... $scope.products = dataService.getJsonData(); console.log($scope.products); The corresponding code in my dataservice is as follows: .service('dataService', function ($http) { t ...