简体   繁体   English

使用Nuxt中间件进行用户重定向和身份验证

[英]User redirect and authentication with middleware of Nuxt

I'm trying to redirect a user to a login page if the user is not logged in when he tries to access certain pages with the following code. 如果用户尝试使用以下代码访问某些页面时未登录,则我试图将其重定向到登录页面。

// middlware/authenticated.js
import firebase from 'firebase'

export default function ({ store, redirect }) {
  let user = firebase.auth().currentUser   
  store.state.user = user //this doesn't work
  if (!user) {
    console.log('redirect')
    return redirect('/login')   
  }
}

However, the problem is with this code when I refresh a page I'm redirected to login page although without using the middleware, I can stay in the same page with logged in. For some reasons, which I don't know why, firebase can't work in middleware. 但是,当我刷新重定向到登录页面的页面时,问题就出在此代码上,尽管无需使用中间件,我仍然可以登录并停留在同一页面上。由于某些原因,我不知道为什么,firebase不能在中间件中工作。

How should I modify this middleware or implement this function? 我应该如何修改该中间件或实现此功能?

Thanks. 谢谢。

//middleware/authenticated.js
export default function ({
  store,
  redirect
}) {
  if (!store.getters['index/isAuthenticated']) {
    return redirect('/login')
  }
}
//post.vue
  async mounted () {
    if (process.browser) {
      let user;
      if (!this.user) user = await auth(); // this auth is a plugin
      await Promise.all([
        this.user ? Promise.resolve() : this.$store.dispatch("setUser", { user: user || null })
      ]);
      this.isLoaded = true;
    }
  },
//plugins/auth.js
import firebase from '~/plugins/firebase'

function auth () {
  return new Promise((resolve, reject) => {
    firebase.auth().onAuthStateChanged((user) => {
      resolve(user || false)
    })
  })
}
export default auth

By default Firebase persists the users logged in status on successful authentication. 默认情况下,Firebase会在成功身份验证后保留用户登录状态。 This example uses the session, to store the user uid and cookies to store the users token and used in situations where the sessions has ended (example when browser is closed) and then a new session started but where the user is still authenticated according to Firebase. 此示例使用会话存储用户uid,并使用cookie存储用户令牌,并在会话结束(例如关闭浏览器)然后启动新会话但仍根据Firebase对用户进行身份验证的情况下使用。 In cases like these the user will not need to sign in to view protected resources. 在这种情况下,用户无需登录即可查看受保护的资源。

Your basic Middleware to protect it should look like this (if you have a Store Module called User) 保护它的基本中间件应如下所示(如果您有一个名为User的存储模块)

export default function ({ store, redirect }) {
  if (!store.getters['modules/user/isAuthenticated']) {
    return redirect('/auth/signin')
  }
}

In your main Store you use the ServerInit Function to get the User if there is one saved in the Cookies and load it into your User Store Module which will be used for verification in the Middleware. 主存储中,如果Cookie中保存了一个,则使用ServerInit函数获取用户,然后将其加载到用户存储模块中,该模块将在中间件中用于验证。

Your User Store Module should look like this , and keep in mind that you remove the Cookie when you Log the User out so that he is fully logged out. 您的用户存储模块应该看起来像这样 ,并请记住,当您注销用户时,您将删除Cookie,以使其完全注销。

I used the things i mentioned above as the beginning of my Authentication and modified it a bit, which you can also do. 我将上面提到的内容用作身份验证的开始,并做了一些修改,您也可以这样做。 Most of the credit goes to davidroyer who has set up this nice Github Repo which includes all needed files as a good example on how to accomplish your goal. 大部分功劳归功于davidroyer,他建立了这个不错的Github Repo ,其中包括所有需要的文件,作为如何实现目标的一个很好的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM