Auth-module: Redirected when going from "/login" to "/" via a navigation guard.

Created on 14 Jun 2020  ·  28Comments  ·  Source: nuxt-community/auth-module

When the user logout redirect to the login page, the redirect happens but i got the Redirected when going from "/login" to "/" via a navigation guard. error

nuxt.config.js

  auth: {
    strategies: {
      local: {
        endpoints: {
          login: { url: 'api/auth/login', method: 'post' },
          logout: { url: 'api/auth/logout', method: 'post' },
          user: { url: 'api/user', method: 'get', propertyName: 'user' }
        },
        tokenRequired: false,
        tokenType: false,
      }
    },
    redirect: {
      logout: '/login',
    },
  },
  router: {
    middleware: ['auth']
  },

login.vue

export default {
  layout: 'auth',
  auth: 'guest',
}

logout button

    async logout() {
      await this.$auth.logout()
    }

20200613_210548

Most helpful comment

I finally found a solution to avoid this error:

  1. Add home: false to the redirect config
redirect: {
  login: '/authentication/login',
  logout: '/authentication/login',
  callback: false,
  home: false
},
  1. Add the redirect after being logged. In my case :
async login() {
  try {
    await this.$axios.$get('/sanctum/csrf-cookie')
    await this.$auth.loginWith('local', { data: this.form })
    (...)
    this.$router.push({ path: '/dashboard' })
  } catch {
    (...)
  }
}

Hope this will help

All 28 comments

Same issue here. It's work well but I have the same error in console.
My config :

auth: {
    redirect: {
      login: '/login',
      logout: '/login',
      callback: false,
      home: '/'
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: '/login',
            method: 'post',
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          },
          logout: {
            url: '/logout',
            method: 'post',
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          },
          user: {
            url: '/api/user',
            method: 'get',
            propertyName: false,
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          }
        },
        tokenRequired: false,
        tokenType: false
      }
    }
  },
  router: {
    middleware: ['auth']
},

Same issue here. It's work well but I have the same error in console.
My config :

auth: {
    redirect: {
      login: '/login',
      logout: '/login',
      callback: false,
      home: '/'
    },
    strategies: {
      local: {
        endpoints: {
          login: {
            url: '/login',
            method: 'post',
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          },
          logout: {
            url: '/logout',
            method: 'post',
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          },
          user: {
            url: '/api/user',
            method: 'get',
            propertyName: false,
            withCredentials: true,
            headers: {
              'X-Requested-With': 'XMLHttpRequest',
              'Content-Type': 'application/json'
            }
          }
        },
        tokenRequired: false,
        tokenType: false
      }
    }
  },
  router: {
    middleware: ['auth']
},

I thought it was just happening to me, because I've already tried it in two new projects from scratch and it's the same problem

I got this behaviour too, don't know how to solve.

On the other hand you guys are setting router middleware inside auth object. You must set it globally

the router middleware it's outside off the auth object, i dont know if this is either an error or what beacuse the redirect works

Same issue here. Using latest version of @nuxtjs/auth-next package.

Somebody can help to this issue, reproduce the issue using CodeSandbox and Mocky? (https://designer.mocky.io)

Example: https://codesandbox.io/s/nuxt-starter-n4b6v-n4b6v

That's help to check the config and files and why the bug happen.

These are the versions I'm using

  "dependencies": {
    "@nuxtjs/auth": "^4.9.1",
    "@nuxtjs/axios": "^5.3.6",
    "nuxt": "^2.13.0"
  }

And this is the example with the issue: https://codesandbox.io/s/nuxt-starter-n4b6v-igmc4
in the console the error appears when i login and then logout
image

Having the same issue 👍

Same

Same hope this get's fixed or the error gets ignored at least

I finally found a solution to avoid this error:

  1. Add home: false to the redirect config
redirect: {
  login: '/authentication/login',
  logout: '/authentication/login',
  callback: false,
  home: false
},
  1. Add the redirect after being logged. In my case :
async login() {
  try {
    await this.$axios.$get('/sanctum/csrf-cookie')
    await this.$auth.loginWith('local', { data: this.form })
    (...)
    this.$router.push({ path: '/dashboard' })
  } catch {
    (...)
  }
}

Hope this will help

Still same issue here.

Login works excellent including the me/user call. URL in address bar is changed as we would expect; the content is loaded as well but the only thing visible is the login page.
However; if I reload I keep the login state (= good) and the token as well and I'll see the correct content.

What to do?

Thanks.

Same. The workaround works well. But of course, having to manually redirect after login sort of defeats the purpose.

well I was facing the problem fixed it by by converting the method to async await, the router was trying the push the path and did not wait for the creds to be received from the server

well I was facing the problem fixed it by by converting the method to async await, the router was trying the push the path and did not wait for the creds to be received from the server

I didn't know it was a promise

I finally found a solution to avoid this error:

  1. Add home: false to the redirect config
redirect: {
  login: '/authentication/login',
  logout: '/authentication/login',
  callback: false,
  home: false
},
  1. Add the redirect after being logged. In my case :
async login() {
  try {
    await this.$axios.$get('/sanctum/csrf-cookie')
    await this.$auth.loginWith('local', { data: this.form })
    (...)
    this.$router.push({ path: '/dashboard' })
  } catch {
    (...)
  }
}

Hope this will help

this solution will remove navigation guard. 😲

I finally found a solution to avoid this error:

  1. Add home: false to the redirect config
redirect: {
  login: '/authentication/login',
  logout: '/authentication/login',
  callback: false,
  home: false
},
  1. Add the redirect after being logged. In my case :
async login() {
  try {
    await this.$axios.$get('/sanctum/csrf-cookie')
    await this.$auth.loginWith('local', { data: this.form })
    (...)
    this.$router.push({ path: '/dashboard' })
  } catch {
    (...)
  }
}

Hope this will help

When I add home: false field, the problem was solved. Thnx :)

Any one has a fix to this yet?

The solution above works but it will remove the navigation guard.

Hi @kempsteven. @mohamadrezahedayati's solution worked on my nuxtjs project.
My nuxt.config.js auth part is like this:

auth: {
    redirect: {
      login: '/login',
      logout: '/login',
      home: false
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/v1/user/sign_in', method: 'post', propertyName: 'user.auth_jwt' },
          logout: { url: '/api/v1/user/sign_out', method: 'delete' },
          user: { url: '/api/v1/user/me', method: 'get', propertyName: 'user' }
        },
        tokenName: 'auth-token'
      }
    }
  }

@kartalsez Yes i believe it should work, but that will remove the navigation guard, try changing your url to /login when youre authenticated

@kempsteven maybe you could use an own middleware for public routes to solve the issue. Something like that:

// ./middleware/public.js

export default function ({ store, redirect }) {
  if (store.getters.isAuthenticated) {
    return redirect('/')
  }
}

Anyway. Thanks @Dimidel. That solves the error for the moment but as mention before it ships some drawbacks everyone should keep in mind.

I managed to remove the error after adding home: false. But i still get NuxtError is not defined which is there with the original error.

Vue Devtools shows that ```loggedIn:true```` while my token already expired. If i explicitly click logout, then no issue until token expired again.

Same problem

Hello everyone who has this issue or same this! The reason of this issue comes from the router of latest version Nuxt that is not compatible to router of Auth module.
We can fix this by this way:
Step 1: disabled rediect to home of Auth module config

// nuxt.config.js (or nuxt.config.ts)
auth: {
    redirect: {
      home: false,
    },
}

Step 2: in login form, you must redirect after login successful by yourself

// Call login method
// Then check callback rediect
if (this.$auth.$state.redirect) { // If rediect to login page from page that is required authentication (auth midleware), go that page
  this.$router.push(this.$auth.$state.redirect);
} else { // Otherwise, go to home page
  this.$auth.redirect('home');
}

Hope useful to you!

As stated in the nuxt auth docs, both this.$auth.loggedIn and this.$store.state.auth.loggedIn indicates whether the user is authenticated or not. They seem to always return the same value.

I don't know why but sometimes they return different values against expectation.

export default {
  data() { ... },
  methods: {
    async login() {
      await this.$auth.loginWith('local', {
        data: {
          auth: { ... }
        }
      }).then((response) => {
        // do something
      }, (error) => {
        // handle errors
      });
      const token = await this.$auth.getToken('local')
      await this.$apolloHelpers.onLogin(token)
      console.log('this.$store.state.auth.loggedIn: ' + this.$store.state.auth.loggedIn)
      console.log('this.$auth.loggedIn: ' + this.$auth.loggedIn)
    }
  }
}

スクリーンショット 2020-12-07 14 37 19

Is this related to the incompatibility?

The reason of this issue comes from the router of latest version Nuxt that is not compatible to router of Auth module.


Here is a part of my package.json:

{
  "dependencies": {
    "@babel/core": "^7.11.6",
    "@babel/preset-env": "^7.12.7",
    "@nuxtjs/auth": "^4.9.1",
    "@nuxtjs/axios": "^5.12.2",
    "nuxt": "^2.14.7",
  },
  "devDependencies": {
    "@nuxt/typescript-build": "^2.0.3",
  }
}

EDIT: https://github.com/nuxt-community/auth-module/issues/437 seems relevant

In my case it's not redirecting neither in login or logout but the requests are being sucessfuly called

async signIn() {
  this.loading = true
  await sleep(1000)
  try {
    await this.$auth.loginWith('local', {
      data: {
        email: this.email,
        password: this.password,
      },
    })
  } catch (e) {
    if ((e as AxiosError).isAxiosError) {
      this.error = (e as AxiosError).response?.status
    }
  } finally {
    this.loading = false
  }
}
// logout page
<template>
  <div></div>
</template>

<script>
export default {
  created() {
    this.$auth.logout()
  },
  layout: 'auth',
}
</script>

```ts
// nuxt.config.js
{
router: {
middleware: ['auth'],
},

auth: {
redirect: {
home: '/',
login: '/auth/signin',
logout: '/auth/signin',
},
watchLoggedIn: true,
strategies: {
local: {
token: {
property: 'authToken',
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/auth/dash-login', method: 'post' },
logout: { url: '/auth/logout', method: 'put' },
user: { url: '/auth/self', method: 'get' },
},
},
},
},
}
```

https://user-images.githubusercontent.com/12385467/103926119-43d35680-50f7-11eb-85f3-5ca2f0d7c825.mp4

I found the problem. As you can see in the video above, there is an error about duplicated store namespaces.
The namespaces are:

@Module({ name: 'auth/signin', stateFactory: true, namespaced: true })
@Module({ name: 'auth/recover-password', stateFactory: true, namespaced: true })

I jsut changed them to

@Module({ name: 'signin', stateFactory: true, namespaced: true })
@Module({ name: 'recover-password', stateFactory: true, namespaced: true })

and now it's working perfectly

I've lost the plot here. What's the issue? Just that a console message appears stating an error? I took a look at @MrJmpl3 but I'm not sure what I need to do to reproduce the issue, or even what I'm looking for. And @Pacheco95's solution is code that's not present in this code base?

It would be most helpful if someone could write a concise summary of the problem and what's expected instead. Thanks :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

amjadkhan896 picture amjadkhan896  ·  3Comments

AhmedAtef07 picture AhmedAtef07  ·  3Comments

nilskoppelmann picture nilskoppelmann  ·  3Comments

DiegoGallegos4 picture DiegoGallegos4  ·  3Comments

yuwacker picture yuwacker  ·  3Comments