1

目标是让 /login 作为唯一的公共路由,一旦登录用户就有基于用户角色的路由。使用 Keycloak 完成身份验证我从 keycloak.idTokenParsed.preferred_username 获取用户:管理员、经理、工程师、操作员。如果操作员尝试转到角色受限路由,则会被重定向到 /notauthorized 页面。(此部分未完成)如果未登录用户将被重定向到 /login 页面。(这部分已完成/工作)

有一个更好的方法吗?在 Routes.jsx 中不重复路由和添加其他用户有点乱。如何实现角色受限重定向到 /notauthorized?

App.js(没有 mapStateToProps、mapDispatchToProps 和导出默认 App 的所有导入和缺少的底部部分)

import React, { useEffect } from "react";
import { Route, Redirect, Switch } from "react-router-dom"

let routeWithRole = [];
let user = '';

const AppContainer = ({ keycloak }) => {
  if(keycloak && keycloak.token) {
    user = keycloak.idTokenParsed.preferred_username
    if( user === 'admin') {
      routeWithRole = admin;
    } else if( user === 'engineer') {
      routeWithRole = engineer
    } else if(user === 'manager') {
      routeWithRole = manager
    } else {
      routeWithRole = operator
    }
  }

   return (
    <div>
          {(keycloak && keycloak.token) ?
            <React.Fragment>
                <Switch>

                  {routeWithRole.map((prop, key) => {
                    console.log('App.js Prop & Key ', prop, key)
                    return (
                      <Route
                        path={prop.path}
                        key={key}
                        exact={true}
                        component={prop.component}
                      />
                    );
                  })}
                  <Redirect from={'/'} to={'/dashboard'} key={'Dashboard'} />
                </Switch>
            </React.Fragment>
            :
            <React.Fragment>
              <Switch>
                {publicRoutes.map((prop, key) => {
                  return (
                    <Route
                      path={prop.path}
                      key={key}
                      exact={true}
                      component={(props) =>
                        <prop.component
                          keycloak={keycloak}
                          key={key} {...props} />
                      }
                    />
                  );
                })}
                <Redirect from={'/'} to={'/login'} key={'login'} />
              </Switch>
            </React.Fragment>
          }
      </div>
  )
}

Routes.jsx(缺少所有进口商)

export const publicRoutes = [
  { path: "/login", type: "public", name: "landing page", component: LandingPageContainer },
]

export const admin = [
  { path: "/createUser", name: "Create User", component: CreateUser},
  { path: "/editUser", name: "Edit User", component: EditUser},
  { path: "/createdashboard", name: "Create Dashboard", component: CreateDashboard },
  { path: "/editashboard", name: "Edit Dashboard", component: EditDashboard },
  { path: "/createcalendar", name: "Create Calendar", component: CreateCalendar },
  { path: "/editcalendar", name: "list of factories", component: EditCalendar },
  { path: "/dashboard", name: "Dashboard", component: Dashboard }
]

export const engineer = [
  { path: "/createdashboard", name: "Create Dashboard", component: CreateDashboard },
  { path: "/editashboard", name: "Edit Dashboard", component: EditDashboard },
  { path: "/dashboard", name: "Dashboard", component: Dashboard },
  { path: "/notauthorized", name: "Not Authorized", component: Notauthorized }
]

export const manager = [
  { path: "/createcalendar", name: "Create Calendar", component: CreateCalendar },
  { path: "/editcalendar", name: "Edit Calendar", component: EditCalendar },
  { path: "/dashboard", name: "Dashboard", component: Dashboard },
  { path: "/notauthorized", name: "Not Authorized", component: Notauthorized }
]

export const operator = [
  { path: "/dashboard", name: "Dashboard", component: Dashboard },
  { path: "/notauthorized", name: "Not Authorized", component: Notauthorized }
]
4

1 回答 1

2

当我们在反应初始化之前知道“keycloak”时,我会考虑这个选项(不是“keycloak”的异步加载数据)。如果你理解了这个想法,你将能够改进

主要思想是显示所有路线,但几乎所有路线都是受保护的路线。请参阅示例:

render (
  <Switch>
    <Route exact path="/login"> // public route
      <LandingPageContainer />
    </Route>
    <AuthRoute exact path="/dashboard"> // for any authorized user
      <Dashboard />
    </AuthRoute>
    <AdminRoute path="/create-user"> // only for admin route
      <CreateUser />
    </AdminRoute>
    <AdminOrEngineerRoute path="/create-dashboard"> // only for admin or engineer route
      <CreateDashboard />
    </AdminOrEngineerRoute>
    <Redirect to="/dashboard" /> // if not matched any route go to dashboard and if user not authorized dashboard will redirect to login
  </Switch>
);

然后你可以像这样创建组件列表:

const AVAILABLED_ROLES = ['admin', 'engineer'];

const AdminOrEngineerRoute = ({ children, ...rest }) {
  const role = keycloak && keycloak.token ? keycloak.idTokenParsed.preferred_username : '';

  return (
    <Route
      {...rest}
      render={({ location }) =>
        AVAILABLED_ROLES.includes(role) && ? (
          children
        ) : (
          <Redirect
            to={{
              pathname: "/login",
              state: { from: location }
            }}
          />
        )
      }
    />
  );
}

因此 AdminOrEngineerRoute 将只允许管理员或工程师传递到此路由,否则您将获得 /login 页面

永远属于你的“IT's Bruise”

于 2020-04-13T16:37:13.637 回答