Auth-module: Prevent User Request on index page(before login) Not Working : Laravel sanctum (Token Based Authentication))

Created on 13 Sep 2020  路  14Comments  路  Source: nuxt-community/auth-module

I'm Using Nuxt Auth Module With Laravel Sanctum

Issue are
the user request is being sent automatically when the page starts, even though I'm not login or trying to login

image

my nuxt.config.js file is :
auth: { strategies: { local: { endpoints: { login: { url: '/login', method: 'post', propertyName: 'token' }, logout: { url: '/logout', method: 'post' }, user: { url: '/user', method: 'get', propertyName: 'user' }, }, } }, redirect: { login: '/login', logout: '/login', callback: '/login', home: '/dashboard' } },

image

I'm also trying user property to (propertyName: false ) or (propertyName: ' ' ) but not working

store/auth.js
`export const getters = {
authenticated(state, getters, rootState){
return rootState.auth.loggedIn;
},

user(state, getters, rootState){
    return rootState.auth.user;
}

}`

How to Stop this first request for a user that automatically occurs. any solutions

All 14 comments

For me what works best is to disable the user endpoint entirely like that:

auth: {
    strategies: {
      cookie: {
        cookie: {
          name: 'XSRF-TOKEN',
        }
      },
      'laravelSanctum': {
        provider: 'laravel/sanctum',
        url: process.env.API_BASE_URL,
        endpoints: {
          login: {
            url: '/api/login',
          },
          logout: {
            url: '/api/logout',
          },
          user: false // Setting user to false will disable to automatic call entirely, so you can have more control.
        },
        tokenRequired: false, //Optional
        tokenType: false, //Optional
        autoFetchUser: false //Optional
      },
    },
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: '/profile'
    }
  },

And to avoid the user request immediately after login (because it would be redundant) just return your user info on the login POST response and then:

this.$auth
        .loginWith('laravelSanctum', { data: this.loginForm })
        .then(res => {
          this.$auth.setUser(res.data.data)
          this.$router.push('/profile')
        })

After that you can even take advantage of that and only make a request on reload, something like that:

beforeCreate() {
if (process.client && !this.$auth.user || this.$auth.user.length) {
      this.$axios.$get('/api/user')
        .then(res => {
          this.$auth.setUser(res.data)
        })
        .catch(err => {
          this.$auth.logout()
          //   Your error handler
        })
    }
}

In other words:
1) Disable the user endpoint by setting it as user: false in nuxt.config.js
2) Return the user info in the login response on success, and use this.$auth.setUser() method to set the user manually.
3) Find a way to check if you don't have the user data already and only then proceed with the request, this will ensure that when you reload the page you won't be logged out, note that it would work out with mounted() hook instead of beforeCreate too.

@nikolayandreev on page refresh user object remove
how to handle this scenario ?

@nikolayandreev
where we can call this method

`beforeCreate() {
   if (process.client && !this.$auth.user || this.$auth.user.length) {
  this.$axios.$get('/api/user')
    .then(res => {
      this.$auth.setUser(res.data)
    })
    .catch(err => {
      this.$auth.logout()
      //   Your error handler
      })
    }
}`

@KamranMaqbool Hi, the user object diassapearing on refresh is expected behaviour because it's stored in vuex, and vuex delete everything on refreah by default.

And that's why you execute the piece of code you mentioned in the layout file, on mounted or beforeCreate hooks, to set the user if it's not found in vuex. Keep in mind that it might be neccessary to check for user.id because user returns empty Object, and won't respond to !user properly. Hope that helps

@nikolayandreev we will use this piece of code on every page?

@nikolayandreev we will use this piece of code on every page?

No in layouts/default.vue or layouts/admin.vue and it will be runned once on reload only.

@KamranMaqbool Did that worked, forgot to tag you..

@nikolayandreev yes it's working fine
thanks

@KamranMaqbool
You don't have to use custom implementations this fallback is default offered by the module to determine authentication state.
So as currently due to axios it is bugged there are two request fired one from ssr context and another from client

Hi @KamranMaqbool! We've made several improvements to the module and hopefully this issue has been fixed in v5. Would you mind to test if it still persist in latest version of auth v5? Thank you :)

Docs here: https://auth.nuxtjs.org/

P.S. Sorry for close/reopen

@JoaoPedroAS51
This should not be issue there

Closing here, due to inactivity. Feel free to reopen if the issue persist.

When i use axios in beforeCreate that throw :"Cannot set headers after they are sent to the client" error

Was this page helpful?
0 / 5 - 0 ratings

Related issues

DiegoGallegos4 picture DiegoGallegos4  路  3Comments

varna picture varna  路  4Comments

ishitatsuyuki picture ishitatsuyuki  路  4Comments

Amoki picture Amoki  路  3Comments

nilskoppelmann picture nilskoppelmann  路  3Comments