Security authentication of web applications is crucial. It enables a personalized experience, loads user-specific content (such as login status), and can also be used to evaluate permissions to prevent unauthorized users from accessing private information.
Applications typically protect content by placing content under a specific route and building redirection rules, directing users to access or away from resources based on their permissions. In order to reliably place content behind protected routes, independent static pages need to be built. In this way, the redirection rules can handle redirection correctly.
For single page applications (SPAs) built with modern front-end frameworks such as Vue, redirect rules cannot be used to protect routing. Because all pages come from a single entry file, from a browser's point of view, there is only one page: index.html. In SPA, routing logic usually originates from routing files. This article will mainly configure authentication here. We will specifically rely on Vue's navigation guards to handle authentication specific routes, as this helps us access selected routes before the route is fully parsed. Let's dig into how it works.
Routing Basics
Navigation Guard is a specific feature in Vue Router that provides additional features about how routing resolves. They are primarily used to handle error states and seamlessly guide users without abruptly interrupting their workflow.
There are three major categories of guards in Vue Router: global guards, router exclusive guards and component guards. As the name implies, the global guard is called when triggering any navigation (i.e. when the URL changes), the route exclusive guard is called when calling the associated route (i.e. when the URL matches a specific route), and the component guard is called when creating, updating, or destroying components in the route. In each category, there are other ways to give you more granular control over application routing. Here is a quick breakdown of all the methods available in each navigation guard in Vue Router.
Global Guard
-
beforeEach
: Operation before entering any route (this scope cannot be accessed) -
beforeResolve
: Action before navigation confirmation, but after component guard (same as beforeEach, with access to this scope) -
afterEach
: Operation after routing resolution (cannot affect navigation)
Route exclusive guard
-
beforeEnter
: Operation before entering a specific route (unlike the global guard, this guard can access this)
Component Guard
-
beforeRouteEnter
: Actions performed before navigation confirmation and before component creation (this cannot be accessed) -
beforeRouteUpdate
: The operation performed after calling a new route using the same component -
beforeRouteLeave
: Operation before leaving the route
Protect routing
To implement them effectively, it will be helpful to know when to use them in any given scenario. For example, if you want to track page views for analysis, you might want to use the global afterEach guard because it is triggered after the route and related components are fully parsed. If you want to prefetch data into Vuex storage before route parsing, you can use the beforeEnter route exclusive guard to do so.
Since our example deals with protecting specific routes based on user access rights, we will use component guards, i.e., beforeEnter hooks. This navigation guard allows us to access the correct route before parsing is complete; this means we can get data or check if the data is loaded before allowing the user to pass. Before digging into the implementation details of how it works, let's briefly take a look at how the beforeEnter hook is incorporated into our existing routing files. Below is our sample routing file containing our protected routes, aptly named protected. We will add the beforeEnter hook to it as follows:
const router = new VueRouter({ routes: [ ... { path: "/protected", name: "protected", component: import(/* webpackChunkName: "protected" */ './Protected.vue'), beforeEnter(to, from, next) { // Logic here} } ] })
Routing structure
The structure of beforeEnter is no different from other navigation guards available in Vue Router. It accepts three parameters: to
, the "future" route to which the application is navigating; from
, the "current/imminent past" route to which the application is leaving; next
, the function that must be called to make the route resolve successfully.
Generally, when using Vue Router, next is called without any arguments. However, this assumes a permanent state of success. In our case, we want to ensure that unauthorized users are unable to access protected resources and that there are alternative paths that can be properly redirected. To do this, we will pass a parameter to next. To do this, we will use the route name to navigate the user, if they are unauthorized, it looks like this:
next({ name: "dashboard" })
Let's assume in our example we have a Vuex store where we store the user's authorization token. To check if the user has permissions, we will check this store and fail appropriately or through the route.
beforeEnter(to, from, next) { // Check vuex storage// if (store.getters["auth/hasPermission"]) { next() } else { next({ name: "dashboard" // Return to secure route// }); } }
To ensure that events occur synchronously and that the route does not load prematurely until the Vuex operation is complete, let's convert the navigation guard to use async/await.
async beforeEnter(to, from, next) { try { var hasPermission = await store.dispatch("auth/hasPermission"); if (hasPermission) { next() } } catch (e) { next({ name: "dashboard" // Return to secure route// }) } }
Remember the source
So far, our navigation guards have achieved their purpose of preventing them from accessing protected resources by redirecting unauthorized users to where they might be from (i.e., dashboard pages). Even so, such a workflow is destructive. Since the redirection is unexpected, the user may think it is a user error and try to access the route repeatedly, ultimately thinking that the application is corrupted. To solve this problem, let's create a method to let users know when and why they are redirected.
We can do this by passing query parameters to the next function. This allows us to attach the protected resource path to the redirect URL. So if you want to prompt the user to log in to the app or get the right permissions without remembering where they stopped, you can do so. We can access the path of the protected resource through the to route object passed to the beforeEnter function, as shown below: to.fullPath.
async beforeEnter(to, from, next) { try { var hasPermission = await store.dispatch("auth/hasPermission"); if (hasPermission) { next() } } catch (e) { next({ name: "login", // Return to secure route// query: { redirectFrom: to.fullPath } }) } }
notify
The next step in enhancing the workflow for users to not have access to protected routes is to send them messages to let them know about the error and how to resolve the issue (by logging in or getting the correct permissions). To do this, we can use component guards, especially beforeRouteEnter, to check if redirects have occurred. Since we pass the redirect path as a query parameter to our routing file, we can now check the routing object to see if the redirect has occurred.
beforeRouteEnter(to, from, next) { if (to.query.redirectFrom) { // Do something// } }
As I mentioned earlier, all navigation guards must call next to make the route resolve. As we saw earlier, the advantage of next function is that we can pass an object to it. What you may not know is that you can also access Vue instances in next function. Wow! This is what it looks like:
next(() => { console.log(this) // this is a Vue instance})
You may have noticed that when using beforeEnter, you are not technically accessing this scope. While this may be the case, you can still access the Vue instance by passing the vm to the function, like so:
next(vm => { console.log(vm) // this is a Vue instance})
This is especially convenient because you can now easily create and properly update data properties with relevant error messages without any additional configuration. Using this method, you will get a component like this:
<template><div> {{ errorMsg }} ... </div> </template> <script> export default { name: "Error", data() { return { errorMsg: null } }, beforeRouteEnter(to, from, next) { if (to.query.redirectFrom) { next(vm => { vm.errorMsg = "對(duì)不起,您沒有訪問請(qǐng)求路由的權(quán)限" }) } else { next() } } } </script>
in conclusion
The process of integrating authentication into your application can be tricky. We explain how to prevent unauthorized users from accessing routes and how to build a workflow based on user permissions to redirect users to or away from protected resources. So far, our assumption is that you have configured authentication in your application. If you haven't configured it yet, and you want to get it up and running quickly, I highly recommend using Authentication as a Service. There are some providers like Netlify's authentication widget or Auth0's lock.
The above is the detailed content of Protecting Vue Routes with Navigation Guards. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
