【问题标题】:how to auth the user in vue 3?如何在 vue 3 中对用户进行身份验证?
【发布时间】:2021-07-20 04:25:17
【问题描述】:

我在使用 vue 3 (vue-cli) 和 vue-router 4 在我的应用程序中登录用户时遇到问题

这是 router.js

import { createRouter, createWebHistory } from 'vue-router';

import store from '../store';

import AuthLayout from "../layouts/AuthLayout";
import DashboardLayout from "../layouts/DashboardLayout";
import PageNotFound from "../views/errors/PageNotFound";

import Login from "../views/auth/Login";
import Logout from "../views/auth/Logout"
import Dashboard from "../views/dashboard/Dashboard";

let routes = [
  {
    path: '/',
    redirect: 'dashboard',
    component: DashboardLayout,
    children: [
      {
        path: '/',
        component: Dashboard,
        name: 'dashboard',
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/logout',
        component: Logout,
        name: 'logout',
        meta: {
          requiresAuth: true
        }
      },
      {
        path: '/:pathMatch(.*)*',
        component: PageNotFound,
        name: 'page-not-found',
        meta: {
          requiresAuth: true
        }
      }
    ]
  },
  {
    path: '/',
    redirect: 'login',
    component: AuthLayout,
    children: [
      {
        path: '/login',
        component: Login,
        name: 'login',
        meta: {
          requiresVisitor: true
        }
      },
    ]
  }
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: routes,
  linkExactActiveClass: 'active'
});

// eslint-disable-next-line no-unused-vars
router.beforeEach((to, from) => {
  if (to.meta.requiresAuth && !store.state.authenticated) {
    return {
      name: 'login',
    }
  }
})

export default router;

我在路由中导入商店以访问经过身份验证的状态。当服务器对用户进行身份验证时,则身份验证 = true。

经过身份验证的(来自 vuex 的状态)......现在是真的......但它停留在登录表单。如果我强制进入/(仪表板),它会再次返回登录。

用户已登录。

任何人都知道我在 routes.js 中缺少什么???

***** 更新 *****

登录组件

export default {
  name: "Login.vue",
  setup() {
    const axios = inject('$axios')
    const store = useStore()
    const authenticated = computed(() => store.state.authenticated)

    const auth = ref( {
      email: '',
      password: ''
    })

    const authUser = () => {
      axios.get('/api/user').then(response => {
        store.commit('setAuthenticated',true);
        store.commit('setUser', response.data)
      })
    }

    const handleLogin = () => {
      // eslint-disable-next-line no-unused-vars
      axios.post('/login', auth.value).then(response => {
        authUser()
      }).catch(error => {
        console.log(error)       
      })
    }

    onMounted(() => {
      // eslint-disable-next-line no-unused-vars
      axios.get('/sanctum/csrf-cookie').then(response => {
        authUser()
      })
    })

    return { auth, handleLogin, authenticated }
  }
}

【问题讨论】:

  • 当服务器对用户进行身份验证时,然后身份验证 = true - 这可能是问题所在,但未显示。
  • @EstusFlask 我已经更新了帖子(发布了登录组件)
  • 我在这里看到了一些潜在的问题,但没有必要进入无关的东西。你能澄清一下你的意思是什么如果我强制进入/(仪表板)它会再次返回登录。重定向是由router push还是手动更改网址完成的?
  • 我的意思是强制(手动更改 url)从 /login 到 /
  • 我就是这么想的。另外,您是将登录凭据存储在 localStorage 还是 cookie 中?

标签: vue.js vue-router vuejs3 vue-router4


【解决方案1】:

我认为,问题在于身份验证状态不是持久的。这意味着,如果您重定向(使用手动 url 更改)或刷新,数据就会消失。

您可以通过

添加持久性
const state = {
  authenticated: localStorage.getItem('authenticated')==='true'; // get authentication from local storage
}
const store = createStore({
  state: state,
  mutations: {
    setAuthenticated(state, payload) {
      state.authenticated = payload;
      localStorage.setItem('authenticated', payload); // sill store 'true' in local storage
    }
  }
})

这会将authenticated 状态存储在您的localStorage 中。它在实例化时填充存储 state.authenticated 值,并在更改时更新。

还有一些其他的考虑,比如重定向

    const authUser = () => {
      axios.get('/api/user').then(response => {
        store.commit('setAuthenticated',true);
        store.commit('setUser', response.data);
        router.push('/'); // <= will redirect after the values are set
      })
    }

【讨论】:

  • 持久性存在于 store.state.authenticate 上。如果刷新页面,我会在登录表单中输出该值并且为真......无论如何......我在authUser 函数中设置了router.push({name: 'dashboard'});,现在它重定向......但如果我改变路线( router-link)到另一个页面(例如:/category)并刷新......它返回到/(仪表板)。我在注销时设置了requiresAuth: true,因为用户需要登录才能注销:)
  • 我已经按照你所说的设置了经过身份验证的状态authenticated: localStorage.getItem('authenticated')==='true'; 并在突变localStorage.setItem('authenticated', payload); 中更新了它,现在它可以工作了。我不明白为什么,因为如果刷新页面,authenticated 状态为真。如果是持久性问题,刷新页面时应该重置为默认值false。使用localStorage 存储状态authenticated 是否安全?
  • 我怀疑authUser 在路由执行后运行并登录了用户
猜你喜欢
  • 1970-01-01
  • 2013-03-11
  • 2021-11-30
  • 2012-05-06
  • 1970-01-01
  • 2021-06-11
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多