【问题标题】:How to set scope(or role) of nuxt $auth.user?如何设置 nuxt $auth.user 的作用域(或角色)?
【发布时间】:2023-05-30 06:53:01
【问题描述】:

我正在使用 nuxt-auth 和 google oauth2 配置,这是我的 nuxt.config.js 配置:

auth: {
  scopeKey: 'scope',
  strategies: {
    google: {
      client_id: process.env.GOOGLE_KEY,
      codeChallengeMethod: '',
      scope: ['profile', 'email'],
      responseType: 'token id_token'
    }
  },
  redirect: {
    login: '/login',
    logout: '/logout',
    home: '/',
    callback: '/welcome'
  }
},
router: {
  middleware: ['auth']
},

我使用此代码登录

this.$auth.loginWith('google')

我想在成功登录后为用户(访问应用程序数据库)设置一个角色,所以我将此代码添加到我的 welcome.vue(oauth2 回调页面)

<script>
export default {
  mounted () {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
  }
}
</script>

但此代码永远不会被调用,因为应用程序会立即重定向到用户在访问登录页面之前选择的页面(welcome.vue html 标记显示 1 秒)。

登录后立即为 this.$auth.user 设置一些属性的正确方法是什么?在 OAUTH2 身份验证后,是否有一些简单的方法可以为用户设置角色?

【问题讨论】:

  • 是什么导致你的应用重定向?是自动还是手动重定向到最后一页? @BogdanTimofeev
  • @Batuhan 它是自动重定向到用户在登录前选择的页面,我正在使用'auth'中间件,编辑了帖子
  • 即我转到 localhost:3000/apps 页面,它会将我重定向到 localhost:3000/login,我使用 Google 登录,它会将我重定向到 localhost:3000/welcome,然后立即返回localhost:3000/apps - 但现在显示此页面是因为我已获得授权

标签: vue.js oauth-2.0 nuxt.js


【解决方案1】:

用户角色必须来自服务器,从客户端定义它是错误的, 但如果这很重要,你可以这样做:

this.$auth.loginWith('google').then(() => {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
})

【讨论】:

  • 我已经尝试过了,但是 then() 回调从未执行,因为在我选择我的谷歌帐户后页面发生了变化
  • 'some_role_from_db' 应该来自服务器,例如它是常量
  • 好的,然后用你的用户对象获取它
  • 用户对象来自谷歌,它没有关于我的特定应用程序中的角色信息,角色应该存储在我的应用程序数据库中
【解决方案2】:

我已将此部分添加到 nuxt.config.js 中的身份验证对象中

rewriteRedirects: false

所以我的应用程序总是将我重定向到home url,并且在主页上我可以访问 auth 对象,如

<script>
export default {
  mounted () {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
  }
}
</script>

【讨论】:

    最近更新 更多