繁体   English   中英

ScopeKey 在 nuxt.js 身份验证模块中不起作用

[英]ScopeKey doesn't work in nuxt.js auth module

最近我开始学习如何使用 Nuxtjs,在学习如何使用它的 Auth 模块时,我遇到了一个问题。

我能够登录并且我想检查帐户的范围,我尝试使用“Auth”的“scopeKey”属性来进行。 从后端,我从数据库中获取“范围”,它可以是“用户”或“管理员”。

我试图设置范围

scopeKey: 'scope'

但是我在检查时发现范围是“未定义”/“空”

this.$auth.hasScope('admin') / this.$auth.hasScope('user')

或“this.$auth.hasScope(admin)”在将“scopeKey”设置为时返回一个空值

scopeKey: 'data.scope'

或者

scopeKey: 'user.scope'

这是我的身份验证策略:

auth: {
    strategies: {
      local: {
        scopeKey: 'scope',
        endpoints: {
          login: {
            url: 'api/auth/login',
            method: 'post',
            propertyName: 'token',
          },
          logout: {
            url: 'api/auth/logout',
            method: 'get'
          },
          user: {
            url: 'api/me',
            method: 'get',
            propertyName: data
          }
        }
      }
    },
    redirect: {
      login: '/auth/login',
      logout: '/',
      callback: '/auth/login',
      home: '/dash/'
    }
  }

这是我登录时 auth 模块读取的 json 示例:

"data": {
        "id": 2,
        "name": "test1",
        "email": "test@test.com",
        "email_verified_at": null,
        "scope": "admin",
        "created_at": "2019-08-01 13:11:49",
        "updated_at": "2019-08-01 13:11:49"
    },

我可以访问前端页面上的范围值

$auth.user.scope

或与

$auth.$state.user.scope

但是如何在设置“auth”属性/策略时为 nuxt.config.js 文件中的“scopeKey”属性指定“范围”?

编辑:

我尝试将它移到 auth 对象内或删除该属性,但在$auth.hasScope('admin')$auth.hasScope('user')上仍然为 false,这意味着scopeKey仍未定义,我不确定为什么。

scopeKey: 'scope'不应放在里面strategies对象。

将其直接放在auth对象中。

看看默认配置

PS您甚至可以从auth config对象中删除此属性,因为'scope'scopeKey默认值。

scopeKey默认为'scope'。 您无需再次设置。

对我来说,它通过更改服务器端而起作用。

当我将字符串值放在作用域中时,它不起作用

$data['scope'] = "admin";

但是,当我将其更改为数组时, $auth.hasScope('admin')可以工作;

$data['scope'] = array("admin", "test");

希望能帮助到你。

不知何故, hasScope()对我也不起作用,所以我直接检查了用户对象,我的响应中也有令牌。 我的响应中有一个类型变量,它告诉我用户是管理员还是其他人。

将此添加到您的中间件中

export default function ({ $auth, redirect }) {

    if (!$auth.loggedIn) {
        return redirect('/')
    }
    if ($auth.user.type != 'Super Admin') {  // Super Admin or whatever the user you want to check
        return redirect('/')
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM