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

Angular directive ceases to trigger

I am currently working on implementing an infinite scrolling directive. Initially, when the page loads and I start scrolling, I can see the console log. However, after the first scroll, it stops working. It seems like it only triggers once. Can anyone poi ...

Need help setting up automatic audio playback on your Android device?

I'm aware that autoplay of audio is not supported on Android devices. However, I recently found a website that successfully autoplays music on an Android device: Can someone explain how this is being achieved? ...

Ways to take an item out of your shopping cart

Do you have any ideas on how to handle cart redirection in JavaScript? My specific request involves a cart with a function that removes products. What approach should I take to redirect to the main page if the cart becomes empty? Here is the delete produc ...

What is the best way to save a large array to a .txt file in node.js?

It seems that using fs.writeFile is the obvious solution. However, after reading the response to this question, it appears that a Stream technique might be more appropriate. In an attempt to delete a line from a text file by converting it to an array, I ...

Combining Django, Graphene, Apollo, django-webpack-loader, and Vue: Struggling with CORS and CSRF compatibility issues?

Currently, I am immersed in a project that involves Django as the backend, Vue as the frontend, and Apollo/Graphene/GraphQL as the data transfer layer. While most of it is functioning smoothly, I am encountering difficulties with the CORS/CSRF settings. I ...

Do we always need to use eval() when parsing JSON objects?

<!DOCTYPE html> <html> <body> <h2>Creating a JSON Object in JavaScript</h2> <p> Name: <span id="jname"></span><br /> Evaluated Name: <span id="evalname"></span><br /> <p> <s ...

Passing data from an Express middleware to a Jade template

My KeystoneJS app is all set up, using Express and Jade. The default.jade file sets up a fullscreen background image along with various imports, the header, and footer of the site. I am attempting to rotate the image based on a selection of images stored ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

Completing Forms with KendoUI Autocomplete

I am currently working with a KendoUI Autocomplete feature within a <form>. One issue I have encountered is that if the user presses the enter key while the autocomplete options are displayed, it only closes the options without submitting the form. S ...

The jQuery UI Dialog is experiencing an issue with a button that is triggering a HierarchyRequest

I am facing an issue with a piece of javascript that works perfectly on other pages but is now throwing a HierarchyRequestError on a new page. This leads me to believe that there may be an HTML problem on this particular page. Here is a simplified version ...

Is it possible to embed a Microsoft Teams meeting within an Iframe?

Is it possible for MS Teams to provide a URL of a video meeting that can be embedded in external locations, such as an iframe on my website? I attempted to add it like this: <iframe src="https://teams.microsoft.com/l/meetup-join/19%3ameeting_N2E3M ...

Mongoose is unable to update arrays, so it will simply create a new array

Having trouble updating my collection without any errors. Can someone lend a hand? I've been at this for 3 hours now. const product_id = req.body.cartItems.product_id; const item = cart.cartItems.find(c => c.product_id == product_id); i ...

Setting the Height of a Fixed Element to Extend to the Bottom of the Browser Window

I currently have a webpage layout featuring a header at the top, a fixed sidebar on the left side, and main content displayed on the right. A demo version of this layout can be viewed at http://jsbin.com/iqibew/3. The challenge I'm facing is ensuring ...

Is it possible to combine JavaScript objects using TypeScript?

Currently, I am dealing with two objects: First Object - A { key1 : 'key1', key2 : 'key2' } Second Object - B { key1 : 'override a' } I am looking to combine them to create the following result: The Merged Re ...

Implementing the 'keepAlive' feature in Axios with NodeJS

I've scoured through numerous sources of documentation, Stack Overflow threads, and various blog posts but I'm still unable to make the 'keepAlive' functionality work. What could I be overlooking? Here's my server setup: import ex ...

Adjusting information using reactivity in VueJS

My goal is to decrement the value of a data property every second in Vue.js using the following code snippet: data() { return { timer: null } }, mounted() { this.timer = 50; window.setInterval(() => { this.$set(this, ...

Are there any security risks in transmitting a password over HTTPS using jsonp?

Is it secure to send a password in JSONP using jquery over HTTPS for authentication if I can't use a JSON POST? EDIT: $.ajax({ type : "POST", url: "https://example.com/api.php", dataType: "jsonp", jsonp: "callback", data: { ...

My Vue frontend project is encountering an error during compilation that states "this relative module module was not found."

I have created a vue frontend to interact with my spring backend, which is working well. However, when I compile the frontend, it compiles to 98% and shows an error message: ERROR Failed to compile with 1 error 11:24:51 The relative module was not foun ...

Using PHP and JavaScript to determine device screen width and eliminate the $_GET parameters from the URL

I have implemented the following JavaScript code to detect screen width and utilize it as a constant throughout my template files using conditional statements to control the visibility of different sections on my site. Just to clarify, I am working within ...

Organize divs based on their attributes

Using inspiration from this SO post, my goal is to group divs based on their "message-id" attribute. The idea is to wrap all divs with the same "message-id" in a div with the class name "group". <div class="message" message-id="1"> ...