Node.js 在MERN web应用程序中实现基于角色的身份验证
我想在我的React应用程序中实现角色库身份验证。。。我正在mongodb中存储管理员和角色Node.js 在MERN web应用程序中实现基于角色的身份验证,node.js,reactjs,express,mongoose,Node.js,Reactjs,Express,Mongoose,我想在我的React应用程序中实现角色库身份验证。。。我正在mongodb中存储管理员和角色 现在 1) 如何在登录应用程序时获取用户角色。。。我将登录数据存储在令牌中…这些令牌存储在浏览器的localstorage中,每个令牌都有过期时间 这就是猫鼬模式 email: { type: String, require: true }, password: { type: String, require: t
现在 1) 如何在登录应用程序时获取用户角色。。。我将登录数据存储在令牌中…这些令牌存储在浏览器的localstorage中,每个令牌都有过期时间 这就是猫鼬模式
email: {
type: String,
require: true
},
password: {
type: String,
require: true
},
roles: {
type: String,
default: "editor"
}
这是我的react 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>
);
};
我用的是casl。。现在是安全使用还是有更好的方法在react应用程序中实现用户角色
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;
//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;