[英]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.