Vue.js navigation guards, restrict access to all unauthorized routes, grant entry to specific routes upon successful authentication

I'm currently working on implementing a navigation guard in Vue.js with a specific logic: I want to restrict access to all routes that require authentication and redirect users to the login page if they are not authenticated. The only exception is the login route, which should allow users to sign in without getting stuck in a loop (this part is proving challenging for me). Once a user is authenticated, they should be able to access both restricted and non-restricted routes.

In summary, I aim to permit access to non-restricted routes, facilitate signing in, and prevent unauthorized access to restricted routes.

If my logic seems unclear or flawed, please feel free to provide feedback as I have been grappling with this issue for some time and could benefit from another perspective.

Below is the code snippet I am working with:

The code is primarily based on a tutorial from bezkoder.com and insights gained from a Vue course by Maximilian Schwarzmuller on Udemy, where I was introduced to navigation guards for the first time.

main.js


import { createApp } from 'vue'
import router from './router/index.js';
import App from './App.vue'
import TheNav from './components/TheNav.vue'
import  { store } from './store/index.js';
import VueParticles from 'vue-particles';

var app = createApp(App);

router.beforeEach((to, from, next) => {
    // Navigation guard logic implementation goes here
})

app.use(router);
app.use(store);

app.config.productionTip = false;

app.component('app-nav', TheNav);

app.use(VueParticles);

app.mount('#app');

auth.module.js The auth module is exported in the store/index.js. So it's the store.

import AuthService from '../services/auth.service';

// Auth module implementation details go here

For the complete project, you can find the code repository at the following link: https://github.com/mupml/PeopleZone-Spring-Security-Spring-Boot-Vue.js

As previously mentioned, there may be fundamental flaws in my approach.

I am also using a Spring backend with a MySQL database: https://github.com/mupml/person-search-spring-boot-vue-security

The current issue I am facing is that while the navigation guard effectively blocks access to restricted routes, it fails to function properly when trying to log in.

Answer №1

After some troubleshooting, I managed to resolve the issue. By utilizing console.log within the before each function, I was able to pinpoint that the getter method I was trying to access from the store was undefined. This caused none of the conditions within the before each function to be satisfied. To fix this, I modified my code to directly access the store state instead of using the getter isAuthenticated. Although using getters is considered best practice, it wasn't effective in this scenario. It's possible that the placement of the code (main.js instead of within a Vue component) could have been a contributing factor.

router.beforeEach((to, from, next) => {
    console.log(store.state.auth.status.loggedIn);
    if(to.path != '/login' && to.meta.requiredAuth && !store.state.auth.status.loggedIn){
        next('/login');
    } else if (from.path == '/login' && to.meta.requiredAuth && store.state.auth.status.loggedIn){
        console.log('this hit')
        next();
    } else {
        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

What is the best method for testing routes implemented with the application router in NextJS? My go-to testing tool for this is vitest

Is it possible to test routes with vitest on Next.js version 14.1.0? I have been unable to find any information on this topic. I am looking for suggestions on how to implement these tests in my project, similar to the way I did with Jest and React Router ...

Resolving issues with jQuery's live() method while incorporating AJAX calls

One of the challenges I'm facing is with buttons on a webpage that are part of the class "go". The code snippet below demonstrates how I handle actions related to these buttons: $(".go").live('click', this.handleAction); The issue arises w ...

"Patience is key when waiting for the alert dialog response in Vuetify

I currently have a reusable component called Alert.vue. <v-dialog v-if="alertDict" v-model="alertDict.showDialog" max-width="460"> <v-card> <v-card-title>Title</v-card-title> & ...

Retrieving information from an API and presenting it as a name with a link to the website

I am attempting to retrieve information from an API and present it in the format Name + clickable website link. Although I have managed to display the data, the link appears as text instead of a hyperlink. Here is my Ajax script: $(function() { ...

In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text fil ...

Issue with Struts 2 tag causing malfunction in validating the collection

When iterating through a list in a JSP file using Struts 2 tags, the code below is used: <%@ taglib prefix="s" uri="/struts-tags"%> <head> ... The issue arises with date validation. The following line of code does not work: <td><s:d ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

Guide on integrating Select2 with webpack

I recently acquired the select2 node module with this command: npm install select2 After adding it to my app.js: require('select2')($); Although no errors appear when I use webpack, upon opening the application, I encounter: Uncaught TypeEr ...

When the clearOnBlur setting is set to false, Material UI Autocomplete will not

I recently encountered an issue in my project while using Material UI's Autocomplete feature. Despite setting the clearOnBlur property to false, the input field keeps getting cleared after losing focus. I need assistance in resolving this problem, an ...

AngularJS version 1.5.11 experiencing issues with ng-repeat functionality

Having an application built on angularJS v1.5.11, I encountered a major issue while attempting to use ng-repeat in a table format like below: <tbody> <tr ng-repeat="score in data.result"> <td ng-repeat="item in score"> {{ item }} & ...

Ensuring Form Integrity through jQuery Validation

I am struggling to customize the errorClass and validClass using JQuery validation. I believe that by adding the .validate function and setting the parameters, it should work. However, even though the validation message displays correctly, the classes re ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Most effective method for automatically scrolling down upon page load

Below is the code snippet that I am using: <script type="text/javascript"> window.onload = function () { window.scrollBy(0, 100); } </script> The purpose of this code is to scroll down after the page has fi ...

How can I execute a task following a callback function in node.js?

Is there a way to run console.log only after the callback function has finished executing? var convertFile = require('convert-file'); var source, options; source = 'Document.pdf'; options = '-f pdf -t txt -o ./Text.txt'; ca ...

Utilizing interactions between a JavaScript scrollable container and Python/selenium

My goal is to utilize Selenium/Python in order to automate the process of downloading datasets from . While I am new to Javascript, I am determined to learn and overcome any obstacles that may arise during this project. Currently, I am focusing on the init ...

Tips on using Visual Studio Code to troubleshoot Angular 4 unit tests

I am working on an Angular 4 project with Material design in Visual Studio Code. The setup is done using angular/cli. Currently, I have been writing unit tests using Karma and Jasmine. However, when trying to debug the tests by setting breakpoints, it doe ...

PHP and AJAX concurrent session issue causing difficulties specifically in Chrome browser

TL;DR. I'm encountering an issue in Chrome where different requests are seeing the same value while incrementing a session counter, despite it working fine in Firefox and Internet Explorer. I am attempting to hit a web page multiple times until I rec ...

Is there a way to alter the data type of a JavaScript object?

Currently, I'm developing a browser-based text adventure game that takes inspiration from classics like Hitchhiker's Guide to the Galaxy and the Zork series. In order to allow players to save their progress, I store important objects such as loca ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Incorporating a setup file into my JavaScript project

In my JavaScript project, I have both frontend and backend codes (NodeJS). Here is the folder structure for my production environment: /prod /server sourceCode1.js sourceCode2.js ... sourceCodeN.js index.js ...