I am currently working on authenticating a Vue.js application using Firebase.
One issue I have encountered is that when attempting to access a URL that requires login directly while already logged in, the router checks for authentication state before Firebase has had a chance to return the auth response. As a result, the user gets redirected to the login page even though they are already authenticated.
Is there a way to delay Vue Router navigation until the authentication state has been retrieved from Firebase? I noticed that Firebase stores authentication data in localStorage - would it be secure to use this as a preliminary authentication check? Ideally, I would like to display a loading spinner or some other indicator while the user's authentication status is being verified, and only allow them to access the desired page once authenticated.
In my router/index.js file:
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/example',
name: 'Example',
component: Example,
beforeEnter: loginRequired
}
})
function loginRequired (to, from, next) {
if (authService.authenticated()) {
next()
} else {
next('/login')
}
}
In my auth.js file:
import * as firebase from 'firebase'
var config = {
// firebase config
}
firebase.initializeApp(config)
// Rest of the code here...
In my app.vue file:
<template>
<div id="app">
<p v-if="auth.user !== null">Logged in with {{ auth.user.email }}</p>
<p v-else>not logged in</p>
<router-view v-if="auth.user !== null"></router-view>
</div>
</template>
<script>
import authService from './auth'
export default {
name: 'app',
data () {
return {
auth: authService
}
}
}
</script>