Nuxt Auth模块-如何通过ID /用户名获取用户

时间:2020-05-19 18:16:08

标签: javascript vue.js authentication vuex nuxt.js

我正在尝试将'Nuxt Auth Module'集成到我的Nuxt应用程序中。

https://auth.nuxtjs.org/

我已经配置了代理和身份验证模块,并设置了“本地策略”。

https://auth.nuxtjs.org/schemes/local.html

我的“登录”端点工作正常,并且将“ propertyName”设置为“ access_token”,因为这是我的令牌值所在的位置。我看到'Vuex'将我的'LoggedIn'状态更新为true,我还可以在Chrome的'网络'标签中看到令牌响应。

但是我真的很努力地了解“用户”端点的工作原理。

给出的示例:

auth: {
  strategies: {
    local: {
      endpoints: {
        login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
        logout: { url: '/api/auth/logout', method: 'post' },
        user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
      },
      tokenRequired: true,
      tokenType: 'bearer'
    }
  }
}

以上内容与我的大致相同,“用户”端点如何知道哪个用户已登录?

我正在使用第三方系统进行身份验证,因为我正在将应用程序集成到第三方系统中。他们用于REST的“用户”端点需要一个“ ID”或“ UserName”来返回有关特定用户的详细信息。

我的“登录”响应包含“用户名”,我可以使用它来调用后续的用户端点(如果我知道怎么做)。

有人知道用户端点的工作原理吗?基本上,我需要这样称呼:

          user: {
            url: '/users/${userId}',
            method: 'get',
            propertyName: 'data'
          }

1 个答案:

答案 0 :(得分:2)

也面对这个问题。

我的解决方案:

  1. 将身份验证端点的 user 属性设置为false

    auth: {

     strategies: {
       local: {
         endpoints: {
           login: {
             url: '/api/v1/users/login',
             method: 'post',
             propertyName: 'token'
           },
           logout: {
             url: '/api/v1/users/logout',
             method: 'post'
           },
           user: false
         },
         redirect: {
           login: '/login',
           logout: '/login',
           callback: '/login',
           home: '/'
         },
       }
     }
    

    },

  2. loginWith()之后,您可以使用函数setUniversal(key, value, isJson)保存获取的用户并使用函数getUniversal(key)

    获取它

`

async login(user) {
        await this.$auth.loginWith('local', {
          data: user
        }).then(res => {
          const user = res.data.data.user
          this.$auth.setUser(user)
          this.$auth.$storage.setUniversal('user', user, true)
          console.log(this.$auth.$storage.getUniversal('user'))
          this.$router.push('/')
        }).catch(err => {
          console.log(err.response)
        })
      }
  1. 仅此而已,您在 vuex cookies 中拥有用户,可以在computed: {}中使用代码{{1 }}

PS:要注销,请使用return this.$auth.$storage.getUniversal('user')函数,并在回调中使用logout()无处不在

中将其删除