admin管理员组

文章数量:1410717

I have a Nuxt app setup with @nuxt/auth. The user always get redirected to login page whenever the page is refreshed. I guess the server side of the Nuxt app is not logged in while the client side is logged in. The JWT access token is gotten from an Express API. Please can someone help me to solve this?. Here is my nuxt.config.js

  auth: {
    redirect: {
      login: '/',
      logout: '/',
      home: '/dashboard',
    },
    resetOnError: true,
    rewriteRedirects: true,
    strategies: {
      local: {
        token: {
          property: 'data.accessToken',
        },
        user: {
          property: 'data[0]',
          autoFetch: false,
        },
        endpoints: {
          login: {
            url: '/api/v1/users/login',
            method: 'post',
          },
          logout: false,
          user: {
            url: '/api/v1/users',
            method: 'get',
            propertyName: false,
          },
        },
      },
    },
  },

And my dashboard.vue

export default {
  middleware: ['auth'],



};

I have a Nuxt app setup with @nuxt/auth. The user always get redirected to login page whenever the page is refreshed. I guess the server side of the Nuxt app is not logged in while the client side is logged in. The JWT access token is gotten from an Express API. Please can someone help me to solve this?. Here is my nuxt.config.js

  auth: {
    redirect: {
      login: '/',
      logout: '/',
      home: '/dashboard',
    },
    resetOnError: true,
    rewriteRedirects: true,
    strategies: {
      local: {
        token: {
          property: 'data.accessToken',
        },
        user: {
          property: 'data[0]',
          autoFetch: false,
        },
        endpoints: {
          login: {
            url: '/api/v1/users/login',
            method: 'post',
          },
          logout: false,
          user: {
            url: '/api/v1/users',
            method: 'get',
            propertyName: false,
          },
        },
      },
    },
  },

And my dashboard.vue

export default {
  middleware: ['auth'],



};
Share asked Jan 5, 2021 at 15:41 drtobdrtob 3734 silver badges11 bronze badges 4
  • You can add the middleware directly to your nuxt.config.js with router: { middleware: ['auth'] } and whitelist it per page with export default { auth: false }. On the main issue, do you have a loggedIn set to true in your $auth module ? This is the flag that got checked against the @nuxt/auth module to determine if you're actually logged-in or not. – kissu Commented Jan 5, 2021 at 15:56
  • Thanks for your response. By default, the logged in flag in-store should be false. But after logging in through the log in form, the logged in flag is changed to true and persisted in localstorage with vuex-persistedState library. I noticed that the when I console.log the state in the auth middleware I created, the logged in flag is false (I mean all the store values are in their default state) but the localstorage is having the correct store state. I sense the server side of the nuxt app is not aware of the state changes in the client side. – drtob Commented Jan 6, 2021 at 7:39
  • Since the pages are server-side generated. it picks and use the available default store values (at that moment) instead of the persisted store values in the localstorage – drtob Commented Jan 6, 2021 at 7:40
  • You created your own auth middleware ? The module is giving one itself, maybe there is a conflict here ? I'll post my config in an answer, if it can somehow help. Btw, I yarn generate'ed a project and it's totally fine on my side, as expected. – kissu Commented Jan 6, 2021 at 8:32
Add a ment  | 

2 Answers 2

Reset to default 2

Here is my working nuxt.config.js

export default {
  router: {
    middleware: ['auth'],
  },
  modules: [
    '@nuxtjs/auth-next'
  ],
auth: {
  redirect: {
    login: '/login',
    home: '/',
    logout: '/login',
    callback: false, // not used here in our case
  },
  localStorage: false, // REALLY not secure, so nah
  resetOnError: true, // kick the user if any error happens w/ the auth
  strategies: {
    local: {
      scheme: 'refresh', // used for the refreshToken flow
      token: {
        property: 'access_token',
        maxAge: 3600, // only useful if not detected on the login
      },
      refreshToken: {
        property: 'refresh_token',
        data: 'refresh_token',
        maxAge: 60 * 60 * 24 * 30, // 1 month
      },
      clientId: process.env.IAM_CLIENT_ID, // our application's ID aka browser
      user: {
        property: 'employee',
        autoFetch: false, // no need to fetch the user, will be done in gql
      },
      endpoints: {
        login: { url: '/login', method: 'post' },
        refresh: { url: '/oauth/refresh', method: 'post' },
        user: false, // as told above, this one is not needed
        logout: { url: '/logout', method: 'get' },
      },
      tokenRequired: true,
      tokenType: 'JWT',
    },
  },
  plugins: [
    '~/plugins/nuxt-axios.js',
    { src: '~/plugins/nuxt-auth.js', mode: 'client' },
  ],
}

nuxt-auth.js is a basic logger in case of an error

import $toast from '~/mixins/buefy-toast'

export default function ({ $auth }) {
  $auth.onError((_name, error) => {
    $toast.open({ message: error })
  })
}

Another important part is my login flow (triggered on a form submit)

export default {
  methods: {
    async authMe() {
      const succesfulLogin = await this.$auth.loginWith('local', {
        data: {
          email: this.email,
          password: this.password,
        },
      })
      if (succesfulLogin) {
        await this.$auth.setUser({
          email: this.email,
          password: this.password,
        })
      }
    }
    // ...
  }
}

We do basically not get the user on the API while authenticating, but rather submit the credentials and validate them, then setting the flag manually with the function $auth.setUser. This is the only part that I handle to pass the loggedIn flag to true, the remaining configuration is just project configuration.
We do also have some refreshToken on our JWT but you can totally omit this one.

Axios config file is basically setting our app's needed headers.

The auth middleware is the one ing w/ the @nuxt/auth module itself, I did not wrote it myself. This is totally working (cookies + vuex state) when generated with target: 'static'.

This error is because of the node version, you can install version 16.9.1 and solve the error.

In my case, I had version 18.14.2 and it gave me the /login redirection error because when refreshing the page in SSR mode the server returned the $auth.loggedIn variable as false and mutated to true when I entered the client section. So the middleware always sent the login redirection rule.

In theory, you should add a section in nuxtServerInit to get the cookie that is stored in that variable and add it somewhere haha

But I really don't know if that can be done

本文标签: javascriptuser always redirected to login on refresh in nuxtjs authStack Overflow