How to write vue authentication

王林
Release: 2023-05-11 10:55:36
Original
674 people have browsed it

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) }) } }
Copy after login
  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() } })
Copy after login

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() } })
Copy after login

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() } })
Copy after login

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!

source:php.cn
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!