Home Web Front-end Vue.js How to implement user authentication and authorization in Vue project

How to implement user authentication and authorization in Vue project

Oct 15, 2023 am 09:09 AM
authentication authorization vue-router

How to implement user authentication and authorization in Vue project

How to implement user authentication and authorization in Vue projects

In recent years, the front-end framework Vue has gradually become the mainstream choice for web development. When developing a Vue project, user authentication and authorization are indispensable functions. This article will introduce in detail how to implement user authentication and authorization in the Vue project from the perspective of technical implementation, and provide specific code examples.

1. User authentication

User authentication refers to the process of verifying the user's identity to ensure that the user has legal permission to access the system. Common user authentication methods include username and password verification, third-party login, etc. The following uses username and password verification as an example to introduce the implementation of user authentication in the Vue project.

  1. Create the login page component

In the Vue project, you first need to create the login page component. This component contains input boxes for username and password and a login button. When the user clicks the login button, authentication is performed by calling the backend API.

The sample code is as follows:

<template>
  <div>
    <input v-model="username" placeholder="请输入用户名" />
    <input v-model="password" placeholder="请输入密码" type="password" />
    <button @click="login">登录</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
    };
  },
  methods: {
    login() {
      // 调用登录API,验证用户名和密码
      // 如果验证成功,将用户信息存储到本地或会话存储中
    },
  },
};
</script>
Copy after login
  1. Verify username and password

In the login method, call the backend API to verify the correctness of the username and password. If the verification is successful, the user information can be saved to local storage or session storage to facilitate subsequent access and permission control.

The sample code is as follows:

methods: {
  login() {
    // 调用登录API,验证用户名和密码的正确性
    api.login(this.username, this.password)
      .then(response => {
        const { token, userInfo } = response.data;
        // 将token和用户信息存储到本地存储或会话存储中
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        // 跳转到主页或其他需要认证的页面
        this.$router.push('/home');
      })
      .catch(error => {
        console.error('登录失败', error);
      });
  },
},
Copy after login
  1. Authentication strategy

After user authentication, authentication usually needs to be performed on each page that requires authorization. . You can determine whether the user has permission to access the page by checking the user information in local storage or session storage.

The sample code is as follows:

beforeRouteEnter(to, from, next) {
  // 检查本地存储或会话存储中是否存在用户信息
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    next();
  } else {
    // 用户未登录,跳转到登录页面
    next('/login');
  }
},
Copy after login

2. User authorization

User authorization refers to determining the user's access rights to system resources. In the Vue project, user authorization management can be achieved through the routing guard mechanism. The following uses routing guards as an example to introduce the implementation of user authorization in the Vue project.

  1. Define the routing table

In the Vue project, define the routing table, including pages that require permission control.

The sample code is as follows:

const routes = [
  {
    path: '/home',
    component: Home,
    // 需要进行权限控制的页面,在路由元信息中定义所需的角色
    meta: { requiresAuth: true, roles: ['admin', 'user'] },
  },
  // 其他路由...
];
Copy after login
  1. Authorization in the route guard

Authorization is performed before the route jump through Vue's navigation guard beforeEach judge. Determine whether the user has the permission to access the page based on the role information defined in the user information and routing meta-information.

The sample code is as follows:

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth) {
    // 检查本地存储或会话存储中是否存在用户信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      const { roles } = JSON.parse(userInfo);
      const requiredRoles = to.meta.roles;
      if (roles.some(role => requiredRoles.includes(role))) {
        // 用户具有访问页面的权限
        next();
      } else {
        // 用户权限不足,跳转到无权限页面
        next('/denied');
      }
    } else {
      // 用户未登录,跳转到登录页面
      next('/login');
    }
  } else {
    // 公开页面,无需授权
    next();
  }
});
Copy after login

Through the above code examples, we can implement user authentication and authorization functions in the Vue project. User authentication ensures the legal identity of the user by verifying user name, password and other information. User authorization uses the route guard mechanism to determine whether the user has the authority to access the page before the route jumps. The implementation of these functions can help us build safe and reliable Vue projects.

The above is the detailed content of How to implement user authentication and authorization in Vue project. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1264
29
C# Tutorial
1237
24
Vue.js vs. React: Project-Specific Considerations Vue.js vs. React: Project-Specific Considerations Apr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

The Choice of Frameworks: What Drives Netflix's Decisions? The Choice of Frameworks: What Drives Netflix's Decisions? Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to jump to the div of vue How to jump to the div of vue Apr 08, 2025 am 09:18 AM

There are two ways to jump div elements in Vue: use Vue Router and add router-link component. Add the @click event listener and call this.$router.push() method to jump.

React, Vue, and the Future of Netflix's Frontend React, Vue, and the Future of Netflix's Frontend Apr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

How to jump a tag to vue How to jump a tag to vue Apr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

Netflix's Frontend: Examples and Applications of React (or Vue) Netflix's Frontend: Examples and Applications of React (or Vue) Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

See all articles