Reactjs 使用自定义声明进行路由保护
我正在构建一个需要管理员和用户后端的应用程序,根据用户是否登录,我已设法保护路由。但是,我需要用户不能访问管理员后端 我知道我可以用if语句来实现这一点,但是,似乎什么都不起作用 我正在使用React重定向 目前,管理员有一个“管理员”令牌 理论上,if语句应该是:Reactjs 使用自定义声明进行路由保护,reactjs,firebase,firebase-authentication,Reactjs,Firebase,Firebase Authentication,我正在构建一个需要管理员和用户后端的应用程序,根据用户是否登录,我已设法保护路由。但是,我需要用户不能访问管理员后端 我知道我可以用if语句来实现这一点,但是,似乎什么都不起作用 我正在使用React重定向 目前,管理员有一个“管理员”令牌 理论上,if语句应该是: if (!admin) { redirect to /userindex } else { return content } 我想知道是否有人知道最好的方法 代码 import React, { Component }
if (!admin) {
redirect to /userindex
}
else {
return content
}
我想知道是否有人知道最好的方法
代码
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { Redirect } from 'react-router-dom';
import '../AdminIndex/AdminIndex.scss';
class AdminIndex extends Component {
render() {
// This checks if the user is logged in
const { auth } = this.props
if(!auth.uid) return <Redirect to = '/login' />
return (
<div className="AdminIndex">
<h1> Admin Index</h1>
</div>
)
}
}
const mapStateToProps = (state) => {
// console.log(state);
return {
auth: state.firebase.auth
}
}
export default compose(
connect(mapStateToProps)
)(AdminIndex)
import React,{Component}来自'React';
从'react redux'导入{connect};
从'redux'导入{compose};
从'react router dom'导入{Redirect};
导入“../AdminIndex/AdminIndex.scss”;
类AdminIndex扩展组件{
render(){
//这将检查用户是否已登录
const{auth}=this.props
如果(!auth.uid)返回
返回(
管理索引
)
}
}
常量mapStateToProps=(状态)=>{
//console.log(状态);
返回{
auth:state.firebase.auth
}
}
导出默认组合(
连接(MapStateTops)
)(行政索引)
用于解析令牌的javascript函数
const\u parseJwt=(令牌)=>{
返回JSON.parse(atob(token.split('.')[1]);
};
const user=await firebase.auth().onAuthStateChanged
如果(用户){
const token=await user.getIdToken(true)
常量结果=_parseJwt(令牌)
警报(JSON.stringify(结果,null,2))
}
这不起作用吗?我觉得不错。您是否已登录console.logged auth prop?@Gh05d显示的代码有效。但是,它不允许基于其令牌进行访问,而只允许用户登录或未登录。因此,目前,任何登录的用户都可以访问项目的管理页面。您可以使用管理令牌,或者-更简单-只需在用户令牌中添加一个属性,如admin:true
。所以您可以避免代码重复。@Gh05d目前,我在管理员用户上有一个管理员自定义声明令牌。我只是在努力抓取代币并将其放入我需要的if语句中。通过导航,我根据令牌设置状态,然后根据状态更改导航,但这似乎不起作用。