API Platform + Nuxt - 会话管理

问题描述 投票:0回答:1

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

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

我想要的是Nuxt能够判断我是否登录到Symfony。使用API​​平台为通用Nuxt应用程序执行此操作的正确方法是什么?中间件?服务器中间件? nuxtServerInit?

login nuxt.js api-platform.com
1个回答
0
投票

我有一些有用的东西,所以我想我会回到这里,以防其他人有一些指示。

基本思路是:

  • 在Nuxt端使用中间件来检查在页面呈现的其余部分发生之前我们是否登录到服务器。
  • 在API平台方面,根据here设置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')
        })
    }

我对此并不完全满意,我相信它会更好。但是,沿着这些方向看起来它看起来会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.