如何在Reaction中实现基于多角色的授权

我在应用程序上工作,其中我有不同的多角色(管理员、用户、经理),我想保护管理员的路由不受经理和一般用户的影响,并根据用户角色呈现UI。我试过了,但我失败了,有没有人能帮我实现我的目标。 示例将不胜感激

谢谢


解决方案

请注意,这不是最佳解决方案,仅供您参考。

创建文件RoleBasedRouting.jsx

function RoleBasedRouting({
  component: Component, roles, ...rest
}) {
  return (
    <>
      { grantPermission(roles) && (
      <Route
        {...rest}
        render={(props) => (
          <>
            <Component {...props} />
          </>
        )}
      />
      )}
      {
        !grantPermission(roles) && (
          <Route
            render={() => (
              <>
                <Unauthorized /> // Unauthorized Page View (skippable)
              </>
            )}
          />
        )
      }
    </>
  );
}

像这样在您的路由器中使用它-

<Switch>
     <RoleBasedRouting exact path="/admin" component={AdminPage} roles={['ROLE_ADMIN']} />
     <RoleBasedRouting exact path="/user" component={UserPage} roles={['ROLE_USER']} />
     <RoleBasedRouting exact path="/manager" component={ManagerPage} roles={['ROLE_Manager']} />
     ...............
</Switch>
grantPermission功能中,检查登录的用户是否具有所需的角色。示例-

export const grantPermission = (requestedRoles) => {
  const permittedRoles =  JSON.parse(localStorage.getItem('userRoles'));
 // in case of multiple roles, if one of the permittedRoles is present in requestedRoles, return true;
  return false;
};

要有条件地呈现UI,您可以执行基本相同的操作。编写组件UnlockAccess-

const UnlockAccess = ({ children, request }) => {
  const permission = grantPermission(request); // request = ['ROLE_ADMIN'] / ['ROLE_USER'] / ['ROLE_MANAGER']
  return (
    <>
      {permission && children}
    </>
  );
};

现在,在Dashboard页面中使用UnlockAccess组件,如下所示-

<Dashboard>
    <UnlockAccess request={['ROLE_ADMIN']}>
         <>
              {/*Write code/components for Admin Dashboard*/}
         </>                    
    </UnlockAccess>
    <UnlockAccess request={['ROLE_USER']}>
         <>
              {/*Write code/components for User Dashboard*/}
         </>                    
    </UnlockAccess>
    <UnlockAccess request={['ROLE_MANAGER']}>
         <>
              {/*Write code/components for Manager Dashboard*/}
         </>                    
    </UnlockAccess>
</Dashboard>

相关文章