search
HomeWeb Front-endFront-end Q&AHow to write vue authentication

Vue is a popular front-end framework that offers ease of use and flexibility. When developing Vue applications, it is often necessary to implement user authentication and authorization functions to ensure that only authenticated users can access restricted resources. This article will introduce how to implement authentication in Vue.

  1. Determine the authentication method

Before you start writing the authentication function, you need to determine the authentication method to use. Common authentication methods include role-based access control (RBAC) and permission-based access control (ABAC). RBAC is an access authorization policy that controls access to resources by assigning users to roles and granting specific permissions to each role. ABAC is an access authorization policy that establishes a set of rules between users and resources to determine whether a specific user has access rights.

In Vue applications, the specific steps to implement RBAC or ABAC authentication methods will be different, so you need to choose the appropriate method according to the requirements of the application.

  1. Implementing identity authentication

Before implementing authentication, user identity authentication needs to be implemented. Typically this is done by getting the user's credentials in a login form and sending them to the server for verification. If authentication is successful, a response containing identity information about the user and a token is generated and stored to the application's local storage or a cookie.

The following is a sample code where the user enters their username and password and sends them to the server for verification:

methods: {
  login() {
    axios.post('/auth/login', {username: this.username, password: this.password})
      .then(response => {
        const {user, token} = response.data
        localStorage.setItem('user', JSON.stringify(user))
        localStorage.setItem('token', token)
      })
      .catch(error => {
        console.error(error)
      })
  }
}
  1. Writing a Vue Route Guard

Vue provides a feature called "route guards" that allows developers to attach interceptor functions to routes and call these interceptors at the beginning of navigation, during route exclusive guards, and during route global guards.

In Vue, you can use route guards to implement access control to ensure that only authenticated users can access restricted routes. Here is a sample code where a Vue route guard intercepts authorized routes:

const router = new VueRouter({
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: Dashboard,
      meta: { requiresAuth: true }
    }
  ]
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token') !== null
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next({ name: 'home' })
  } else {
    next()
  }
})

In the above code, when the user tries to access a route marked with "requiresAuth" metadata, the route exclusive guard and the global The routing hook function is called between guards. If the user has authenticated, access to the route is allowed. Otherwise, redirect to the login page.

  1. Implementing RBAC and ABAC authentication

The implementation methods of RBAC and ABAC authentication are different. Simply put, RBAC divides users into roles and permissions and assigns these to already defined roles. ABAC establishes security policies as a collection and enforces these policies upon access requests to determine which users have access to restricted resources.

When implementing RBAC authentication, it is necessary to construct a mapping between user roles and permissions, and assign roles to each user. The application can then decide whether the user has permission to access a specific resource based on the user's role. The following is a sample code:

const roles = {
  admin: {
    permissions: ['user:list', 'user:create', 'user:edit']
  },
  manager: {
    permissions: ['user:list', 'user:edit']
  },
  member: {
    permissions: []
  }
}

function checkPermission(permission) {
  const user = JSON.parse(localStorage.getItem('user'))
  const userRole = user.role
  if (roles[userRole]) {
    return roles[userRole].permissions.includes(permission)
  } else {
    return false
  }
}

const routes = [
  {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
    meta: { requiresAuth: true, permission: 'user:list' }
  }
]

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'login' })
  } else if (to.meta.permission && !checkPermission(to.meta.permission)) {
    next({ name: 'home' })
  } else {
    next()
  }
})

In the above code, the role mapping is stored in the roles object. User roles are determined by user information stored in localStorage. The actual function that checks permissions, checkPermission(), checks whether the user has the specified permissions.

When implementing ABAC authorization, you need to write policies that check how access is used to perform security operations on resources. Take attribute-based access control (ABAC) as an example. ABAC defines a set of rules that check whether a user can access resources based on attributes related to the user (such as role, location, or device owned).

The following is sample code where Vue route guards use attributes to enforce ABAC policies:

const permissions = {
  'user:list': {
    condition: 'user.role === "admin" || user.role === "manager"'
  },
  'user:create': {
    condition: 'user.role === "admin"'
  },
  'user:edit': {
    condition: 'user.role === "admin" || (user.role === "manager" && user.department === "it")'
  }
}

const checkPermission = (permission) => {
  const user = JSON.parse(localStorage.getItem('user'))
  const rule = permissions[permission]
  return rule && eval(rule.condition)
}

const routes = [
  {
    path: '/dashboard',
    name: 'dashboard',
    component: Dashboard,
    meta: { requiresAuth: true, permission: 'user:list' }
  }
]

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'home' })
  } else if (to.meta.permission && !checkPermission(to.meta.permission)) {
    next({ name: 'home' })
  } else {
    next()
  }
})

In the above code, each access authorization rule has a condition attribute that defines that the user must meet properties to access specific resources. The checkPermission() function uses the eval() function to interpret and execute the condition attribute of the rule.

Summary

To implement authentication in a Vue application, you need to determine the authentication method, implement identity verification, write Vue routing guards, and implement RBAC or ABAC authentication. No matter which authentication method is used, Vue route guard is the key technology to achieve authorization. By using Vue route guards and implementing RBAC or ABAC authentication, you can easily authorize access and protect restricted resources in your application.

The above is the detailed content of How to write vue authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is useEffect? How do you use it to perform side effects?What is useEffect? How do you use it to perform side effects?Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading.Explain the concept of lazy loading.Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code?Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

How does currying work in JavaScript, and what are its benefits?How does currying work in JavaScript, and what are its benefits?Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

How does the React reconciliation algorithm work?How does the React reconciliation algorithm work?Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How do you connect React components to the Redux store using connect()?How do you connect React components to the Redux store using connect()?Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

What is useContext? How do you use it to share state between components?What is useContext? How do you use it to share state between components?Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you prevent default behavior in event handlers?How do you prevent default behavior in event handlers?Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.