Search code examples
vue.jsnuxt.jsnuxt-auth

how to keep user authenticated after refreshing the page in nuxtjs?


I'm using laravel passport for API's and nuxt.js for frontend after a successful login if I refresh the page the user is not authenticated anymore and loggedIn returns false, its my first nuxt.js project so I have no idea how to deal with that, any advise is appreciated

login.vue

<script>
import { mapActions } from 'vuex'

export default {
  data() {
    return {
      email: "",
      password: ""
    }
  },
  methods:{
    async login(){
      const succesfulLogin = await this.$auth.loginWith('local', {
        data: {
          email: this.email,
          password: this.password
        },
      })
      this.$store.commit("saveUser",succesfulLogin.data)
      this.$store.commit("saveToken", succesfulLogin.data.token)

      if (succesfulLogin) {
        await this.$auth.setUser({
          email: this.email,
          password: this.password,
        })
        this.$router.push('/profile')
      }
    }
  }
}
</script>

store/index.js

export const state = () => ({
  user:{},
  token: ""
})

export const mutations = {
  saveUser(state, payload) {
    state.user=payload;
  },
  saveToken(state, token) {
    state.token= token
  }
 
}
export const actions = {
     saveUserAction({commit}, UserObject){
         commit('saveUser');
     },
     logoutUser({commit}){
        commit('logout_user')
     }
}
export const getters = {
  getUser: (state) => {
    return state.user
  },
  isAuthenticated(state) {
    return state.auth.loggedIn
  },

  loggedInUser(state) {
    return state.user.user
  }
}

after a successful login enter image description here

after refreshing the page enter image description here


Solution

  • We do use a global middleware right after my auth module authentication

    /middleware/global.js

    export default async ({ app, store }) => {
      if (store?.$auth?.$state?.loggedIn) {
        if (!app.$cookies.get('gql.me_query_expiration')) {
          // do some middleware logic if you wish
    
          await app.$cookies.set('gql.me_query_expiration', '5min', {
            // maxAge: 20,
            maxAge: 5 * 60,
            secure: true,
          })
        }
      }
    }
    

    nuxt.config.js

    router: {
      middleware: ['auth', 'global'],
    },
    

    We're using cookie-universal-nuxt for handling secure cookies quickly, working great!

    While accessing or refreshing the webapp (we do redirect to the /login page if not authenticated) and we use this basic GraphQL configuration where the cookie is needed.

    /plugins/nuxt-apollo-config.js

    export default ({ app }) => {
      const headersConfig = setContext(() => ({
        credentials: 'same-origin',
        headers: {
          Authorization: app.$cookies.get('auth._token.local'), // here
        },
      }))
    
      [...]
    }
    

    Checking gql.me_query_expiration allows us to see if the user has authenticated lately/is currently authenticated or if he needs to refresh his token.
    And auth._token.local is our actual JWT token, provided by the auth module.

    As told above, it is more secure to have a secure cookie than some localStorage, this is also why we are not using it

    nuxt.config.js

    auth: {
      localStorage: false, // REALLY not secure, so nah
      ...
    }