Use Vue to implement page access interception

Use Vue to implement page access interception

In modern web applications, page access interception is a very important aspect. It can be used to ensure that users can only access pages they are authorized to, improving application security and user experience. This blog post will introduce how to use the Vue framework to implement the function of page access interception.

1 Vue routing and navigation guards

1.1 Introduction to Vue Routing

Vue Routing is the official routing library for building Single Page Applications (SPA). It allows developers to switch pages to corresponding components according to different URL addresses, so as to realize no-refresh jump between pages.

In Vue routing, we can define a set of routing rules, each routing rule maps a URL address and the corresponding component. When a user visits a URL address, the routing will find the matching component according to the configured rules and render it to the specified location.

Vue routing provides a variety of navigation methods, including normal link jumps, programmatic navigation, and navigation through browser forward and back buttons.

1.2 Overview of Navigation Guard

Navigation guards are a feature provided by Vue routing for control and management during routing switching. It allows developers to perform some specific logic operations before, after, or when a switch is canceled.

The navigation guard mainly has the following hook functions:

  • beforeEach: Called before each routing switch, it can be used for global permission verification or other pre-operations.
  • afterEach: Called after each routing switch, it can be used for statistics or other post-operations.
  • beforeResolve: Called before each route switch, beforeEachsimilar to, but afterEachcalled before the global call.
  • beforeEnter: A hook function defined in a single route configuration, which is called before entering the route.

Additionally, there are two special navigation guards:

  • beforeRouteUpdate: Called when the current route is reused, such as /user/1navigating from to /user/2.
  • beforeRouteLeave: Called before leaving the current route, it can be used to prompt the user to save unsaved data.

By using navigation guards, we can implement functions such as login verification, permission control, and page jump interception.

2 The core concept of implementing access interception

2.1 Introduction to Routing Guard

2.1.1 Front guard ( beforeEach)

The front guard is a hook function that is called before the route is switched. This can be done by registering a global front guard or a hook defined in the configuration of an individual route beforeEnter.

Use the pre-guard to perform some global permission verification or other pre-operations, such as checking whether the user is logged in, verifying user permissions, and so on. Can be called if current navigation needs to be blocked next(false).

2.1.2 Rear hook ( afterEach)

Post-hook is a hook function that is called after the route is switched. It has no ability to change the navigation itself, only to do some statistics or other post operations.

Post hooks do not receive nexta function parameter, since the navigation cannot be changed.

2.1.3 parse guard ( beforeResolve)

Parse guards are hook functions that are called before the routing component is ready. It is similar to the global pre-guard, but afterEachis called before the global call.

Parsing guards can be used to handle the loading process of asynchronous routing components, ensuring that the necessary data is obtained before rendering components.

2.2 Authentication logic design

Authentication (Authorization) is the core concept of permission-based access control system. When designing authentication logic, the following aspects usually need to be considered:

  1. Definition of roles and permissions: Determine the roles and corresponding permissions in the system, and clearly define and divide them.

  2. User authentication: Implement a user login verification mechanism to ensure that only authenticated users can access restricted resources.

  3. Routing permission control: According to the user's role and permission, permission verification is performed in the routing navigation guard to decide whether to allow the user to access a certain page or perform a certain operation.

  4. Component-level permission control: within the component, according to the user's role and permissions, dynamically display or hide specific functional modules or buttons.

  5. Back-end interface permission control: Perform permission verification at the back-end interface level to prevent unauthorized requests from accessing sensitive data or performing important operations.

By rationally designing and implementing authentication logic, the security of the system and the integrity of data can be effectively protected.

2.3 Login Verification Mechanism

Using the Vue route navigation guard can easily implement the user login authentication mechanism.

First, beforeEachcheck if the user is logged in in the global front guard ( ). If the user is not logged in, you can use to next('/login')redirect the user to the login page.

router.beforeEach((to, from, next) => {
    
    
  const isLoggedIn = checkUserLoggedIn(); // 检查用户是否已登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    
    
    next('/login'); // 重定向到登录页面
  } else {
    
    
    next(); // 继续导航
  }
});

In the route configuration that requires login verification, you can use metathe field to specify that the route requires permission verification.

const routes = [
  {
    
    
    path: '/dashboard',
    component: Dashboard,
    meta: {
    
     requiresAuth: true } // 需要登录验证
  },
  // 其他路由配置...
];

In this way, when the user accesses /dashboardthe path, the global pre-guard will be triggered first for login verification. If the user is not logged in, it will be redirected to the login page; if the user is logged in, it will continue to navigate to the target page.

Through the above methods, we can easily implement the user login verification mechanism based on Vue route navigation guard.

3 Steps to implement page access interception

3.1 Routing configuration

In Vue routing, page access interception is realized by setting routing guard rules. You can configure corresponding guards on the pages that need to be blocked.

First, introduce Vue Router in the project's routing file (usually router.js), and create a new Router instance.

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const router = new VueRouter({
    
    
  routes: [
    // 路由配置信息
  ]
})

Then, add guards to the pages that need to be intercepted in the routing configuration.

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/login',
      component: Login
    },
    {
    
    
      path: '/dashboard',
      component: Dashboard,
      meta: {
    
     requiresAuth: true } // 添加 requiresAuth 元字段表示需要登录验证
    }
  ]
})

In the above code, the component Dashboard of the '/dashboard' path requires login verification.

3.2 Writing guard functions

Next, write the pre-guard function to implement the logic of login verification and permission verification.

router.beforeEach((to, from, next) => {
    
    
  if (to.meta.requiresAuth && !isAuthenticated()) {
    
    
    next('/login') // 如果需要登录验证且未登录,则跳转到登录页面
  } else {
    
    
    next() // 否则继续导航
  }
})

function isAuthenticated() {
    
    
  // 进行登录验证的逻辑,返回 true 表示已登录,false 表示未登录
}

In the above code, the beforeEach function is a global pre-guard that will be executed before each route switch. We can make logical judgments of login verification in it.

If to.meta.requiresAuth is true and the user is not logged in (isAuthenticated() returns false), jump to the login page via next('/login'). Otherwise, call next() to continue navigating to the target page.

3.3 Interception processing

Finally, in the interception processing part, perform corresponding jumps or prompts according to the situation that needs to be intercepted.

In the above code, when login verification is required and the user is not logged in, the user will be redirected to the login page through next('/login').

You can also perform other interception processing according to specific needs, such as permission verification, access restrictions, etc.

In this way, the basic implementation of page access interception is completed.

4 sample demo

4.1 Create a Vue project

To create a simple Vue project, you can use the Vue CLI (command line interface) to quickly set up the project structure. Here are the steps to create a Vue project using Vue CLI:

  1. First, make sure you have Node.js and npm (the Node package manager) installed. You can check if they are installed by running the following command in terminal:

    node -v
    npm -v
    
  2. If Node.js and npm are not installed, please go to Node.js official website (https://nodejs.org/) to download and install.

  3. Next, install Vue CLI globally. Run the following command in a terminal:

    npm install -g @vue/cli
    
  4. Once installed, you can use the following command to create a new Vue project:

    vue create my-project
    

    In this command, my-project is the name of the project you want to create, you can change it according to the actual situation.

  5. After running the above command, Vue CLI will prompt you to select some configuration options. You can use the up and down arrow keys to choose between options and the enter key to confirm. You can choose the default configuration, or customize it according to your needs.

  6. Once configured, Vue CLI will automatically download and install the dependencies required by the project.

  7. After the installation is complete, you can enter the project directory with the following command:

    cd my-project
    
  8. Finally, start the development server with the following command:

    npm run serve
    

    This will start the development server and open the project in the browser. You can access your Vue application at http://localhost:8080 (default port).

With this, you have successfully created a simple Vue project. You can add components, routing, state management and other functions to the project as needed, and use various features of Vue to develop your application.

4.2 Configure page access interception

To add routing guards to a Vue project and configure them accordingly, follow these steps:

  1. Create a auth.jsnew file called , and define a AuthGuardroute guard class in it called .
import {
    
     getToken } from './auth'; // 导入获取 token 的方法

const AuthGuard = (to, from, next) => {
    
    
  const token = getToken(); // 获取 token
  if (token) {
    
    
    // 如果存在 token,允许访问该页面
    next();
  } else {
    
    
    // 如果不存在 token,重定向到登录页面
    next('/login');
  }
};

export default AuthGuard;
  1. router/index.jsImport the class in the file and AuthGuardadd it to the routing configuration that requires page access interception.
import AuthGuard from '@/auth';

const routes = [
  {
    
    
    path: '/dashboard',
    component: DashboardComponent,
    beforeEnter: AuthGuard // 使用 beforeEnter 属性指定路由守卫
  },
  {
    
    
    path: '/profile',
    component: ProfileComponent,
    beforeEnter: AuthGuard
  },
  ...
];

const router = new VueRouter({
    
    
  routes
});

export default router;

In the above example, AuthGuardthe route guard will block access to /dashboardand /profilepaths, allowing access to those pages only if the token is present. If no token exists, it will be redirected to the login page.

4.3 Demo login verification

To demonstrate login authentication and verify the effect of access blocking, you can follow these steps:

  1. auth.jsAdd a method called in the file , loginwhich is used to simulate the user to log in and save the token.
export const login = (username, password) => {
    
    
  // 模拟登录请求,验证用户名和密码
  if (username === 'admin' && password === 'password') {
    
    
    // 登录成功,保存 token 到 localStorage
    localStorage.setItem('token', 'your_token_here');
    return true;
  } else {
    
    
    // 登录失败
    return false;
  }
};
  1. auth.jsAdd a method called in the file to getTokenget the token stored in localStorage.
export const getToken = () => {
    
    
  return localStorage.getItem('token');
};
  1. In the component of the login page, use loginthe method to log in the user, and perform corresponding processing according to the login result.
import {
    
     login } from '@/auth';

export default {
    
    
  data() {
    
    
    return {
    
    
      username: '',
      password: ''
    };
  },
  methods: {
    
    
    handleLogin() {
    
    
      const {
    
     username, password } = this;
      const loggedIn = login(username, password);
      if (loggedIn) {
    
    
        // 登录成功,跳转到首页或其他需要登录的页面
        this.$router.push('/dashboard');
      } else {
    
    
        // 登录失败,显示错误提示
        alert('登录失败,请检查用户名和密码');
      }
    }
  }
};
  1. In the routing configuration that requires page access interception, use beforeEnterattributes to specify routing guards.
import AuthGuard from '@/auth';

const routes = [
  {
    
    
    path: '/dashboard',
    component: DashboardComponent,
    beforeEnter: AuthGuard
  },
  {
    
    
    path: '/profile',
    component: ProfileComponent,
    beforeEnter: AuthGuard
  },
  ...
];

In the above example, loginthe method simulates a user login and saves the token in localStorage. In the component of the login page, call loginthe method to log in, and perform corresponding processing according to the login result. In the routing configuration that requires page access interception, use beforeEnterattributes to specify routing guards.

5 summary

In this technical blog, we learned how to use Vue to implement page access interception. Page access blocking is a common security measure to ensure that only authenticated users can access certain pages or perform certain actions.

Through Vue's navigation guard function, we can intercept before the route switch, and perform authentication or permission check as needed. By using the beforeEach navigation guard, we can execute custom logic before each route switch.

In this blog post, we demonstrated how to create a simple login page and use navigation guards to prevent unauthenticated users from accessing protected pages. We also covered how to use Vue's routing features to set up routing and navigation guards.

Through this example, we can see the flexibility and power of Vue, enabling us to easily implement page access interception. This is critical to building secure web applications.

I hope this blog was helpful and provided you with the basics of blocking page access with Vue. If this interests you, you can further explore Vue's other features and extensions to improve your development skills and build more secure applications.

Guess you like

Origin blog.csdn.net/weixin_55756734/article/details/132181490