首页 > 解决方案 > 在 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;

标签: node.jsreactjsexpressmongoose

解决方案


推荐阅读