【问题标题】:How to use session authentication for nuxt frontend with adonis backend如何在 nuxt 前端和 adonis 后端使用会话身份验证
【发布时间】:2020-07-25 11:48:38
【问题描述】:

我曾经使用 adonuxt,效果很好,但它已经贬值了。所以我现在尝试将 nuxt.js 与 adonis 后端分开使用。我正在尝试制作登录系统。这两个项目在 localhost 的两个独立端口上运行。 http://localhost:3000/nuxt 项目和http://localhost:3333/adonis 项目。

如何在 nuxtServerInit 中获取登录用户信息?

我正在尝试这样

async nuxtServerInit({ commit }, { $axios }) {
 console.log('I am running as nuxt server init')

 try {
   // get the initial data
   let { data } = await axios.get('http://localhost:3333/myuser')
   commit('loginUser', data)
 } catch (e) {
     console.log('nuxt server error ', e.response)
  }
},

在我的 adonis.js 中我正在尝试

async getUser({request, response, params, auth}){
  try {
    const user = await auth.getUser()
    return user
  } catch (error) {
      return 'not logged in'
  }
}

结果总是not logged in....

知道如何实现.....

更新

我正在使用一个非常简单的登录系统

async user({request, response, params, auth}){
   try {
      const user = await auth.loginViaId(34)
      return user
   } catch (error) {
      return error
   }
}

我现在得到了一个非常有趣的结果。因此,如果我使用我的 adonis 项目登录,那么登录的用户信息将在 nuxt 项目中可用,但如果我使用 nuxt axios 登录,我将无法获取登录用户

更新 2

所以,会话登录是有效的,但是使用axios时,adonis找不到用户或登录用户。

更新 3

我们只能使用 nuxtServerInit 获取登录用户.. 我们可以使用 axios.. 获取登录用户.. :(

【问题讨论】:

  • 你能分享你的登录控制器代码吗?
  • 请检查问题,我更新了。
  • 你能把credentials: true添加到axios config (axios.nuxtjs.org/options.html#credentials)
  • 我收到Access to XMLHttpRequest at 'http://localhost:3333/myuser' from origin 'http://localhost:8000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. 错误
  • 我已经启用了 cors 但仍然是这个

标签: nuxt.js adonis.js


【解决方案1】:

配置阿多尼斯

config/session.js

  cookie: {
    httpOnly: true,
    path: '/',
    sameSite: 'strict',
    domain: Env.get('COOKIE_DOMAIN', null),
  },

config/cors.js

  /*
  |--------------------------------------------------------------------------
  | Credentials
  |--------------------------------------------------------------------------
  |
  | Define Access-Control-Allow-Credentials header. It should always be a
  | boolean.
  |
  */
  credentials: true, // Enable credentials cookies

Access-Control-Allow-Credentials 响应标头告诉浏览器是否在请求的凭据模式 (Request.credentials) 为 include 时将响应公开给前端 JavaScript 代码。

有关 Access-Control-Allow-Credentials 标头的更多信息:developer.mozilla.org

配置 Nuxt

启用 axios 凭据 (https://axios.nuxtjs.org/options.html#credentials):

nuxt.config.js

  axios: {
    credentials: true,
  },

【讨论】:

  • 很高兴听到它?
  • 之前没有发送 cookie 信息。知道如何在这种方法中实现 csrf 令牌吗? Adonuxt 是一个救生员 :( 但它已经贬值了....
  • 只需添加 @adonisjs/shield (adonis),启用 csrf 并从 cookie XSRF-TOKEN (nuxt) 中获取 csrf 令牌
猜你喜欢
  • 2020-07-13
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2020-05-11
  • 2018-02-25
  • 1970-01-01
相关资源
最近更新 更多