【发布时间】:2020-12-17 05:51:12
【问题描述】:
我正在使用 Vue 和 firebase 来构建身份验证机制。每次刷新页面时,身份验证都会被丢弃,我会被重定向到登录页面。
我按照documentation 尝试了setPersistence(firebase.auth.Auth.Persistence.SESSION)。我还实现了这个reddit thread 的一些技巧。我仍然被重定向,我注意到在刷新时,auth.onAuthStateChanged((user) => {}) 回调有user = null。
我有点卡住了。抱歉,如果这是一个新手问题。
firebase.js
import * as firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: process.env.VUE_APP_API_KEY,
...
};
firebase.initializeApp(firebaseConfig)
// utils
const db = firebase.firestore()
const auth = firebase.auth()
auth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
// export utils/refs
export {
db,
auth
}
main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from './plugins/vuetify';
import router from './router/index'
import { store } from './store'
import { auth } from './firebase'
Vue.config.productionTip = false
let app
auth.onAuthStateChanged((user) => {
if (!app) {
app = new Vue({
router,
store,
vuetify,
render: h => h(App)
}).$mount('#app')
}
if (user) {
store.dispatch('fetchUserProfile', user)
store.commit('setEmail', user.email)
}
})
路由器/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Login from '../components/Login'
import Dashboard from '../components/Dashboard'
import { auth } from '../firebase'
Vue.use(Router)
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/login',
name: 'login',
component: Login,
meta: {
disableNavBar: true
}
},
// ... other routes removed for brevity
{
path: '/dashboard',
name: 'Dashboard',
component: Dashboard,
meta: {
requiresAuth: true
}
},
]
});
router.beforeEach((to, from, next) => {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
if(to["path"] !== from["path"]){
if(requiresAuth){
auth.onAuthStateChanged(function(user) {
if (user) {
console.log("Logged in", user)
next();
} else {
console.log("Here", user) //this logs user = null on refresh
next('/login')
}
});
} else {
next();
}
}
})
export default router
【问题讨论】:
标签: firebase vue.js firebase-authentication