Is it secure to use Vue Router for navigation?

I am currently working on a web project using Vue, and I have noticed that the following code snippet works when executed in the console:

document.getElementById('app').__vue__.$router.push("some_route")

Despite having meta tags defined in the beforeEach navigation guard (requireAuth), certain routes can still be accessed by unauthorized users. In my Flask API, I return a token and a role for validation purposes. While entering the URL directly in the address bar triggers authentication, accessing the same route through the console bypasses this verification process.

router.beforeEach(async (to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    let user = JSON.parse(localStorage.getItem('user')) // User is a JSON with a JWT token

    if (user && user.token){
      
      await user_service.isLogged(to.path).then(response => {
       // Wait for a response from the server to validate the token
        switch (response.status){
          case 200:
            next()
            break;

          case 401:
            next({path: '/login'})
            break;
          
          case 403:
            next({path: '/403'})
            break;
        }
      })
    } else {
      next({path: '/login'})
    }

  }
  next()
})

Your feedback and suggestions are highly appreciated. Thank you!

Answer №1

It's crucial to ensure that the final next() call is not obstructed, as it renders your navigation guard ineffective.

To address this, you can encapsulate it within an else clause, like so:

if(to.matched.some(record => record.meta.requiresAuth)) {
  // your code
} else {
  next()
}

Alternatively, modify your code to include appropriate exit points using return:

router.beforeEach(async (to, from, next) => {
  if(to.matched.some(record => record.meta.requiresAuth)){
    let user = JSON.parse(localStorage.getItem('user'))

    if (user && user.token){
      await user_service.isLogged(to.path).then(response => {
       //wait for a response from the server if the token is valid
        switch (response.status){
          case 200:
            return next()
          case 403:
            return next({path: '/403'})
          case 401:
          default:
            return next({path: '/login'})
        }
      })
    } else {
      return next({path: '/login'})
    }
  }
  next()
})

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

Creating an array dynamically by parsing a JSON object in Javascript

I am currently working with a JSON object that looks like this: var testJSON = [ { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", " ...

Tips for clicking the OK button in an alert box with Protractor

When working with AngularJS, I encounter the need to delete a link which triggers an alert box for confirmation. While attempting e2e testing using protractor, how can I confirm actions within an alert box? I attempted the following code snippet: browse ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

Instead of returning a single array of data from a form as expected, Jquery is returning two arrays

Having a bit of trouble with my code involving radio buttons and arrays using Jquery. I'm trying to record the selected values into one array, but it's creating separate arrays for each fieldset. Here's what I have: <script> $(doc ...

Trouble with conflicting Javascript on my webpage

I am facing an issue with my web page, where the lightwindow script is not functioning properly due to a conflict with the accordion menu script. When I remove the accordion script, the lightwindow script works fine. I suspect there is a conflict between t ...

Is there a way to split a <v-carousel-item> within a <v-carousel> component into two columns using Vuetify?

I am looking to incorporate this carousel design into vuetify3. How should I go about it? https://i.stack.imgur.com/XQXOC.jpg ...

Send the input's value to v-model

Is there a way to automatically pass the value of the input into the v-model? Thank you :) Here is the code snippet: <input value="{{$in->id}}" v-model="upload.id"> I attempted the following in my script: upload: { bank:'', ...

Automatically fill out form fields by selecting data from a spreadsheet

I successfully created a web application using Google Apps Script (GAS) that sends data on submission to Spreadsheet A. Furthermore, I have implemented a select option that dynamically fetches data from another spreadsheet B ("xxx") in column A. Below is ...

How can I fix the issue of the onClick function in my React list not activating the toggle?

How to Activate Toggle Functionality Currently, I am working on a project using React where I developed a list with active states. I have implemented the onClick functions, but unfortunately, they are not working as intended. When I click on the list item ...

Stopping Popups in Chrome When Printing with JavaScript

Javascript function printPage(htmlPageContent) { var newWindow = window.open("about:blank"); newWindow.document.write(htmlPageContent); newWindow.print(); } In this code snippet, we are creating a new window 'newWindow' and then using ...

Retrieve database SQL information using JavaScript to display data

I'm struggling to push the value from a textbox to SQL and display it. Despite reading numerous topics, I still can't figure it out. My explanation skills are lacking, but hopefully you can understand what I'm trying to achieve, especially i ...

Displaying a three.js canvas in a VUE component without the need for declaring variables outside or using appendChild

I attempted to incorporate three js canvas within a Vue setup. However, due to Vue's state management pattern, I could only achieve this by setting the canvas-related variables outside of Vue's state management. I came across an example that acc ...

Changing position of element upon appearance of span in React

Currently, I am working with React and facing an issue where a span element appears whenever a user hovers over a text element. The problem is that the existing text shifts leftwards when the span appears (to the right of the text). The desired behavior ...

The attempt to retrieve data from the PHP file using Ajax was unsuccessful

I'm attempting to showcase the content of a PHP file on my HTML page using AJAX. Within my HTML file, I have included the following AJAX code: AJAX Code in get_ajax.html <form action=""> First name: <input type="text" id="txt1" onblur="sh ...

Merging Vue.js with vue.router in history mode and Django unfortunately results in an error

When I set publicPath to '/static/' in my webpack configuration, everything works smoothly with my Vue.js app on a Django Webserver for both development and production environments. However, when attempting to implement history mode, I need to m ...

What sets apart passing arguments to a function from utilizing variables at the class level?

As someone who is just starting out in the Typescript and Angular-2 world, my previous experience includes working with Java and Angular-1.5. Imagine a scenario where there is a component class with several variables that need to be used across functions, ...

Fastest method to verify if two arrays share identical values in JavaScript

Is there a more efficient way to determine if two arrays have the same values in JavaScript? The current method I am using is functional but quite lengthy. Here is how I am checking: let arraysAreDifferent = false; array1.forEach(item => ...

Shopify Inventory Dropdown Tailored to Stock Levels

I'm having an issue with my Shopify store. How can I make sure that the quantity dropdown matches the actual items in stock? For instance, if there are only 3 items available, the maximum value in the quantity dropdown should be set to 3. And if there ...

The functionality of res.status().send() appears to be malfunctioning when used within a Promise

I am currently working on a code that involves checking authorization from two different API calls within a promise.all method. If any of the authorizations fail, I want to throw the respective res.send method as an error. However, I keep encountering an " ...