npm install auth-util
或者通过git克隆或下载项目,将auth-util相关文件复制到项目
import AuthUtil from 'auth-util/index';
class Example extends Component {
constructor(props) {
super(props)
this.origin = project.http.authHost;
this.state = {
hasToken: false // 没有token访问非登录页就不渲染,防止无意义的接口调用
}
}
componentDidMount () {
this.authUtil = new AuthUtil({
root: 'auth-util-wrapper',
authHost: this.origin,
onGetUserInfo: this.onGetUserInfo,
onLocalStorageChange: this.onLocalStorageChange
});
this.authUtil.init();
}
redirect = (pathname = this.props.location.pathname) => {
if (localStorage.token) {
this.setState({
hasToken: true
});
} else {
this.setState({
hasToken: false
});
/* 如果没有token跳转到登录页 */
this.authUtil.toLogin()
}
};
/* 获取userInfo后开始显示页面并根据token获取权限 */
onGetUserInfo = () => {
this.setState({
hasToken: true
});
authService.getAuthAction().then(res => {
if (!publicUtils.isOk(res)) return;
localStorage.setItem('authAction', res.data.result);
this.getMenuForPathname();
});
};
/*
更新重新登陆弹窗剩余时间
tokenExpire token结束时间
* */
updateTokenExpTimeMs = (tokenExpire) => {
if (tokenExpire === localStorage.tokenExpire) return;
/* 计算重新token有效剩余时间 */
const tokenExpTimeMs = tokenExpire - new Date().getTime();
GlobalStore.setTokenExpTimeMsValue(tokenExpTimeMs);
GlobalStore.setIsTokenExpTimeMs(false);
};
onLocalStorageChange = (key, value) => {
switch (key) {
case 'tokenExpire':
this.updateTokenExpTimeMs(value);
break;
case 'token':
GlobalStore.setIsTokenExpTimeMs(false);
break;
}
};
logoutTest = () => {
this.authUtil.logout();
};
render() {
return (
<Provider GlobalStore={ GlobalStore }>
<div style={ { height: '100%' } }>
<div id="auth-util-wrapper" hidden></div>
<div style={ { height: '100%' } }>
<div><button onClick={ this.logoutTest }>登出</button></div>
<ConfigProvider locale={ zh_CN }>
<Switch>
<Route path="/login" component={ Login }/>
<Route path='/' component={ this.state.hasToken ? Layouts : '' }/>
</Switch>
</ConfigProvider>
</div>
</div>
</Provider>
)
}
}
export default Routers
root: 必须 --- 根节点id,决定插入位置
authHost: 必须 --- 鉴权系统地址,即现在的综合管理系统
id: iframe的id
iframeProps: 自定义iframe的props
onGetUserInfo: 获取userInfo后的回调
onGetUserInfoFail: 获取userInfo失败后的回调
onLocalStorageChange: 修改localStorage后回调,携带修改的localStorage的key和value,如callback(key, value)
fileNames: localStorage的key重命名,如 { token: 'workbench_token' } 意为将默认key token改为workbench_token
authUtil.init()
初始化
authUtil.postMessage(type, data = {})
向iframe发送消息
authUtil.toLogin(withToken = false)
跳转到鉴权系统登录页,并携带当前地址到url以便返回。可传入true以带回token到url上
authUtil.logout()
登出系统,清除本地包括token等的用户信息,并跳转到综管登录页
authUtil.updateLocalStorage(partialLocalStorage)
发送消息给iframe,通知鉴权系统更新localStorage