1

带有 Nuxt Auth 的 Node.js 应用程序以及当我想登录时。用户未设置并且loggedInfalse

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 },
        },
      },
    },
  },

你能帮我吗?

4

1 回答 1

0

我找到了答案的解决方案。我自己写的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现在它似乎工作了:)

于 2021-04-13T07:09:34.527 回答