Vue page login authentication and access control

More Articles

Page access control

Page access control What does it mean?

Is a website have different roles, such as administrators and ordinary users, requiring different roles can access the page is not the same. If a page, there is the role of unauthorized access, then you have to make limits.

Vue dynamically add routes and the Build menu This is an article I wrote, by adding dynamic routing and control menus to do, can not access the pages are not added to the routing table, which is one way.

Another way is to all pages in the routing table, but in the time of the visit to determine what role permissions. If you have access permissions let no authority to refuse to jump to page 404.

Ideas :

In each routing metaattributes, the role will be able to access the route is added to the rolesinside. After each time the user logged in, the user will return to the role. And then when the page is accessed, the routing metaattributes and user roles comparison, if the user's role in the route roleswhere it is able to access, if not refused access.

Code Example :

Routing Information

routes: [
    {
        path: '/login',
        name: 'login',
        meta: {
            roles: ['admin', 'user']
        },
        component: () => import('../components/Login.vue')
    },
    {
        path: 'home',
        name: 'home',
        meta: {
            roles: ['admin']
        },
        component: () => import('../views/Home.vue')
    },
]
复制代码

Page Control

// 假设角色有两种:admin 和 user
// 这里是从后台获取的用户角色
const role = 'user'
// 在进入一个页面前会触发 router.beforeEach 事件
router.beforeEach((to, from, next) => {
    if (to.meta.roles.includes(role)) {
        next()
    } else {
        next({path: '/404'})
    }
})
复制代码

Login authentication

After landing sites are generally just once, followed by all other pages of the site can be accessed directly, without logging in again. We can pass tokenor cookiebe achieved, with the following code shows how to use tokenthe control login authentication.

router.beforeEach((to, from, next) => {
    // 如果有token 说明该用户已登陆
    if (localStorage.getItem('token')) {
        // 在已登陆的情况下访问登陆页会重定向到首页
        if (to.path === '/login') {
            next({path: '/'})
        } else {
            next({path: to.path || '/'})
        }
    } else {
        // 没有登陆则访问任何页面都重定向到登陆页
        if (to.path === '/login') {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }
})
复制代码

Achieve all of the above, can in my vue lightweight back office systems base template found in projects

Reproduced in: https: //juejin.im/post/5d0af31be51d4576bc1a0e0e

Guess you like

Origin blog.csdn.net/weixin_34168880/article/details/93178449