React Router v5.1.2 Public&受保护的认证和保护基于角色的路线 [英] React Router v5.1.2 Public & Protected Authenticated & Role Based routes
问题描述
目标是将/login作为唯一的公用路由,一旦登录的用户具有基于用户角色的路由. 使用Keycloak进行身份验证我从keycloak.idTokenParsed.preferred_username获取用户:管理员,经理,工程师,操作员. 如果操作员尝试转到角色受限路径,则路由将重定向到/notauthorized页面. (这部分没有完成) 如果未登录,则用户将被重定向到/login页面. (这部分完成/工作)
Goal is to have /login as the only public route, once logged in user has routes based on user role. Authentication is done with Keycloak I get users from keycloak.idTokenParsed.preferred_username: admin, manager, engineer, operator. If operator tries to go to role restricted route gets redirected to /notauthorized page. (This part not done) If not logged in user gets redirected to /login page. (This part is done/works)
是否有更好的方法可以做到这一点?不重复路线在Routes.jsx中添加其他用户有点混乱. 如何实现角色限制重定向到/notauthorized?
Is there a better way to do this? Not repeating routes & adding additional users in Routes.jsx kind of a mess. How do I implement role restricted redirect to /notauthorized?
App.js(不具有mapStateToProps,mapDispatchToProps和导出默认App的所有导入和缺少的底部部分)
App.js (does not have all the imports and missing bottom part with mapStateToProps, mapDispatchToProps & export default 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(缺少所有功能)
Routes.jsx (missing all the impotrs)
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 }
]
推荐答案
当我们在进行初始化之前知道"keycloak"时,我将考虑该选项(而不是异步加载"keycloak"的数据).如果您了解这个主意,您将可以改善
I will consider the option when we have known "keycloak" before react initialization (not async loading data for "keycloak"). You will be able to improve if you understand the idea
主要思想是显示所有路线,但几乎所有路线都是受保护的路线.参见示例:
The main idea is to show all routes but almost all of them will be protected routes. See the example:
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>
);
然后您可以创建如下组件列表:
Then you can create list of components like this:
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页面
As a result AdminOrEngineerRoute will allow to pass to this route only admin or engineer in other case you will get /login page
永远是您的"IT挫伤"
Always yours "IT's Bruise"
这篇关于React Router v5.1.2 Public&受保护的认证和保护基于角色的路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!