Ant Design Pro权限管理组件的使用
权限组件Authorized
是antd pro脚手架权限管理的基础,基本思路是对比当前权限与准入权限,决定展示请求的内容还是异常内容。
权限控制场景
控制菜单和路由显示
控制页面元素显示
登录时权限检查
首先看一下菜单和路由的权限控制,是通过配置路由设置准入权限的:
{
path: ‘/’,
component: ‘../layouts/BasicLayout’,
Routes: [‘src/pages/Authorized’],
authority: [‘admin’, ‘user’],
routes: [
// forms
{
path: ‘/form’,
icon: ‘form’,
name: ‘form’,
routes: [
{
path: ‘/form/basic-form’,
name: ‘basicform’,
component: ‘./Forms/BasicForm’,
},
{
path: ‘/form/advanced-form’,
name: ‘advancedform’,
authority: [‘admin’],//配置准入权限,可以配置多个角色
component: ‘./Forms/AdvancedForm’,
},
],
},
],
}
这里需要注意的是Routes属性,由于使用了umi框架,umi 的权限路由是通过配置路由的 Routes
属性来实现。约定式的通过 yaml 注释添加,配置式的直接配上即可。
那么,Routes设置的组件即为权限组件,可以定义被设置组件的渲染结果,上面src/pages/Authorized设置了权限组件,当通过根路径访问系统时触发权限组件,权限组件内部调用了用户身份的获取方法和相关组件的准入权限,触发时自动比较权限,通过则放行,否则跳转预定义的页面(一般是登录页)。
这就是说,路由的控制既可以控制到菜单路由的展示,也可以控制登录权限。
对页面内部元素的权限控制,就是控制某一元素是否显示(不考虑读写权限之类)。
import RenderAuthorized from ‘ant-design-pro/lib/Authorized’;
import { Alert } from ‘antd’;
const Authorized = RenderAuthorized(‘user’);
const noMatch = <Alert message="No permission." type="error" showIcon />;
ReactDOM.render(
<div>
<Authorized authority="admin" noMatch={noMatch}>
<Alert message="user Passed!" type="success" showIcon />
</Authorized>
</div>,
mountNode,
);
也可以使用数组:
<Authorized authority={[‘user’, ‘admin’]} noMatch={noMatch}>
<Alert message="Use Array as a parameter passed!" type="success" showIcon />
</Authorized>,
也可以使用方法作为参数:
import RenderAuthorized from ‘ant-design-pro/lib/Authorized’;
import { Alert } from ‘antd’;
const Authorized = RenderAuthorized(‘user’);
const noMatch = <Alert message="No permission." type="error" showIcon />;
const havePermission = () => {
return false;
};
ReactDOM.render(
<Authorized authority={havePermission} noMatch={noMatch}>
<Alert
message="Use Function as a parameter passed!"
type="success"
showIcon
/>
</Authorized>,
mountNode,
);
使用注解的方式:
import RenderAuthorized from ‘ant-design-pro/lib/Authorized’;
import { Alert } from ‘antd’;
const { Secured } = RenderAuthorized(‘user’);
@Secured(‘admin’)
class TestSecuredString extends React.Component {
render() {
<Alert message="user Passed!" type="success" showIcon />;
}
}
ReactDOM.render(
<div>
<TestSecuredString />
</div>,
mountNode,
);
声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 嗅谱网
转载请注明:转自《Ant Design Pro权限管理组件的使用》
本文地址:http://www.xiupu.net/archives-9697.html
关注公众号:
微信赞赏
支付宝赞赏