簡體   English   中英

Nuxt.js auth 用戶已設置但已登錄仍為 false

[英]Nuxt.js auth user is set but loggedIn is still false

帶有loggedIn身份驗證的 Node.js 應用程序以及當我想登錄時。未設置用戶且已登錄為false

const response = await this.$auth.loginWith('local', { data: {
   email: this.form.email.value,
   password: this.form.password.value,
} });
this.$auth.setUser(response.data.user);
this.$auth.strategy.token.set(response.data.jwt.access_token)
this.$auth.strategy.refreshToken.set(response.data.jwt.refresh_token)

所以我寫了這個,然后設置了用戶,但loggedIn仍然是假的。 這是我的nuxt.config.js

auth: {
    strategies: {
      local: {
        scheme: 'refresh',
        token: {
          property: 'access_token',
          maxAge: 1800,
          required: true,
          type: 'Bearer',
        },
        refreshToken: {
          property: 'refresh_token',
          data: 'refresh_token',
          maxAge: 60 * 60 * 24 * 30,
        },
        user: {
          property: 'user',
          autoFetch: true,
        },
        endpoints: {
          login: { url: '/login', method: 'post' },
          refresh: { url: '/refresh', method: 'post', propertyName: false },
          logout: { url: '/logout', method: 'post' },
          user: { url: '/refresh', method: 'post', propertyName: false },
        },
      },
    },
  },

你能幫我嗎?

我找到了答案的解決方案。 我寫了自己的scheme

import { RefreshScheme } from '~auth/runtime'

export default class CustomScheme extends RefreshScheme {
  // Override `fetchUser` method of `local` scheme
  async fetchUser (endpoint) {

    this.options.endpoints.user = {
      ...this.options.endpoints.user,
      data: {
        token: this.$auth.strategy.refreshToken.get()
      }
    }

    // Token is required but not available
    if (!this.check().valid) {
      return
    }

    // User endpoint is disabled.
    if (!this.options.endpoints.user) {
      this.$auth.setUser({})
      return
    }

    // Try to fetch user and then set
    return this.$auth.requestWith(
      this.name,
      endpoint,
      this.options.endpoints.user
    ).then((response) => {
      const user = response.data.user

      // Transform the user object
      const customUser = {
        ...user,
        fullName: user.name,
        roles: ['user']
      }

      // Set the custom user
      // The `customUser` object will be accessible through `this.$auth.user`
      // Like `this.$auth.user.fullName` or `this.$auth.user.roles`
      this.$auth.setUser(customUser)

      return response
    }).catch((error) => {
      this.$auth.callOnError(error, { method: 'fetchUser' })
    })
  }
}

顯然是從propertyName獲取用戶的問題。 我用我自己的響應const user = response.data.user替換代碼,現在它似乎工作了:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM