首页 > 解决方案 > API 平台 + Nuxt - 会话管理

问题描述

我是 Nuxt 和 API 平台的新手。我已经创建了一个基本的服务器和客户端,并且正在尝试解决如何进行会话管理。

我可以纯粹在客户端登录,例如使用 Nuxt Auth0 支持。或者我可以滚动自己的登录。但这只是客户端。或者我可以在 Symfony 服务器上使用表单登录并从客户端发布到它,但这只是服务器端。

我想要的是 Nuxt 能够判断我是否登录到 Symfony。对于使用 API 平台的通用 Nuxt 应用程序,正确的方法是什么?中间件?服务器中间件?nuxtServerInit?

标签: loginnuxt.jsapi-platform.com

解决方案


我有一些有用的东西,所以我想我会在这里发帖,以防其他人提供一些指导。

基本思想是:

  • 在 Nuxt 端,使用中间件在页面渲染的其余部分发生之前检查我们是否登录到服务器。
  • 在 API 平台方面,按照此处设置 JWT 身份验证。这给了我们一个令牌,我们将在 API 请求上发送它来验证它们。

在 Nuxt 客户端中,您需要一个存储来处理登录状态。这是我当前的 WIP 版本(所以我并没有声称它是很棒的代码):

import axios from 'axios'

export default function({ store, redirect }) {
  store.commit('security/AUTHENTICATING')

  // Add token header if we have it.
  const token = store.state.security.token

  if (token) {
    axios.defaults.headers.common.Authorization = 'Bearer ' + token.toString()
  } else {
    axios.defaults.headers.common.Authorization = null
  }

  // Now make an API call to see if we're logged in.
  return axios
    .get(process.env.API + '/locations')
    .then(response => {
      // We're logged in.  No need to save the token - it's already in the store.
      store.commit('security/AUTHENTICATING_SUCCESS', null)
    })
    .catch(() => {
      // We're not logged in.
      if (store.state.security.isAuthenticated) {
        // ...but we thought we were. Correct our misapprehension.
        store.commit('security/LOGOUT')
      }

      // Ask them to log in.
      return redirect('/login')
    })
}

然后设置一些中间件:

    import axios from 'axios'
    
    export default function({ store, redirect }) {
      store.commit('security/AUTHENTICATING')
    
      // Add token header if we have it.
      const token = store.state.security.token
    
      if (token) {
        axios.defaults.headers.common.Authorization = 'Bearer ' + token.toString()
      } else {
        axios.defaults.headers.common.Authorization = null
      }
    
      // Now make an API call to see if we're logged in.
      return axios
        .get(process.env.API + '/locations')
        .then(response => {
          // We're logged in.  No need to save the token - it's already in the store.
          store.commit('security/AUTHENTICATING_SUCCESS', null)
        })
        .catch(() => {
          // We're not logged in.
          if (store.state.security.isAuthenticated) {
            // ...but we thought we were. Correct our misapprehension.
            store.commit('security/LOGOUT')
          }
    
          // Ask them to log in.
          return redirect('/login')
        })
    }

我对此并不完全满意,我相信它可能会更好。但是沿着这些思路的东西看起来可以完成这项工作。


推荐阅读