node.js - 在 MERN Web 应用程序中实现基于角色的身份验证
问题描述
我想在我的 React 应用程序中实现角色基础身份验证......我现在在 mongodb 中存储管理员和角色
1)我如何在登录应用程序时获取用户角色......我将登录数据存储在令牌中......它们存储在浏览器的本地存储中,每个令牌都有过期时间这是猫鼬模式
email: {
type: String,
require: true
},
password: {
type: String,
require: true
},
roles: {
type: String,
default: "editor"
}
这是我的反应 app.js 文件
const App = () => {
const { token, login, logout, adminId }= useAuth();
let routes;
if (token) {
routes=(
);
}else{
routes=(
);
}
return(
<AuthContext.Provider
value={{
isLoggedIn: !!token,
token: token,
// editorId: editorId,
adminId: adminId,
login: login,
logout: logout
}}
>
<Router>
<Switch>
{routes}
</Switch>
</Router>
</AuthContext.Provider>
);
};
这是身份验证上下文文件
import {createContext} from 'react';
export const AuthContext = createContext({
isLoggedIn: false,
adminId: null,
token: null,
login: () =>{},
logout: () =>{}
});
我正在使用 casl .. 现在可以安全使用,或者有更好的方法在反应应用程序中实现用户角色 2)我如何将登录的用户角色设置为 casl 能力文件
这是ability.js 文件
//ability.js
import { Ability, AbilityBuilder } from "@casl/ability"
import store from "../store/index"
// Defines how to detect object's type
function subjectName(item) {
if (!item || typeof item === "string") {
return item
}
return item.__type
}
const ability = new Ability([], { subjectName });
function defineRulesFor(auth) {
const { can, rules } = AbilityBuilder.extract()
if (auth.role === "editor") {
can("view", "Profile")
}
if (auth.role === "admin") {
can("accept", "Application")
}
if (auth.role === "viewer") {
can("review", "Proposal")
}
return rules
}
export default ability;
解决方案
推荐阅读
- sql - 获取 NULL 值
- android-studio - 我无法安装包缓存的网络映像
- node.js - JSONata - Nodejs API 中的 JSON 到 JSON 的转换
- javascript - React Native - Tesseract.js - 错误:无法为 blob 创建 URL
- c# - 在 AWS Lambda 函数中使用 PuppeteerSharp
- angularjs - 将 AngularJS 数组传递给降级的 Angular 7 组件
- elasticsearch - 使用纳秒时间戳将文档批量注入弹性搜索
- javascript - 包含方法未检测到数组中的现有项目
- java - 无法从 BLE 设备读取数据,永远不会调用 onCharacteristicChanged()
- c++ - CRecordset::GetFieldValue() 与 BIGINT