Vai*_*rma 6 javascript authentication authorization reactjs react-lifecycle
我正在使用 react js 和 node js api 实现一个简单的用户身份验证系统。这就是我在ComponentWillMount方法中所做的:-
1.检查令牌是否存在(在localStorage中)
2.如果它不存在,那么状态“令牌”的值将保持空白
3.如果它存在,则使用对后端的请求检查它是否有效。
4.如果令牌有效,则状态“令牌”为localstorage.token
5.如果令牌无效,则状态“令牌”的值将保持空白
在渲染方法中,我根据状态“令牌”的值添加了条件渲染,即如果状态“令牌”为空白,则将呈现正常页面,否则将被重定向到用户页面。
问题是我可以使用任何 React 开发人员工具更改状态“令牌”的值。这导致了使用假令牌登录的漏洞。为了避免每次使用componentDidUpdate shouldComponentUpdate等生命周期方法更改状态“令牌”时,我都必须检查它的有效性。但是正如官方文档中提到的
reactshouldComponentUpdate只作为性能优化存在。不要依赖它来“阻止”渲染,因为这可能会导致错误。
使用componentDidUpdate没有用,因为它会在组件因状态改变而改变后被调用。
使用componentWillUpdate在官方文档中被称为 Unsafe
我不知道如何解决这个漏洞。这是组件的代码
import React,{Component} from 'react';
import {
BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';
import Home from './Home';
import Nav from './Nav';
import Login from './Login';
import Signup from './Signup';
class Out extends Component{
constructor(){
super();
this.state = {
token : '',
isLoading:false
}
this.isLoading = this.isLoading.bind(this);
}
logout(){
alert('logged out');
}
componentWillMount(){
let {match} = this.props;
this.navNoSessionRouteData = [
{to:`${match.url}login`,name:'Login',key:'r1'},
{to:`${match.url}signup`,name:'signup',key:'r2'},
{to:`${match.url}`,name:'Home',key:'r3'}
];
this.navNoSessionButtonData = [];
this.setState({
isLoading:true
});
const tokenVar = localStorage.getItem('token');
if(tokenVar == null){
console.log('not logged in');
this.setState({
isLoading:false
});
}else{
fetch('http://localhost:3000/api/account/verify?token='+tokenVar)
.then(res=>res.json())
.then(json=>{
if(json.success){
console.log('logged in');
this.setState({
token : tokenVar,
isLoading:false
});
}else{
this.setState({
isLoading:false,
});
}
});
}
}
isLoading(){
let {isLoading,token} = this.state;
if(isLoading === true){
return (
<p>Loading...</p>
);
}
else{
let {match} = this.props
console.log(token);
return(
<div>
{
(token)?<p>Logged In</p>:(<p>NOT logged IN</p>)
}
<div className = "row">
<Nav navRouteData = {this.navNoSessionRouteData} navButtonData = {this.navNoSessionButtonData}/>
</div>
<div className="row justify-content-center">
<Switch>
<Route exact = {true} path={`${match.path}`} component={Home} />
<Route path={`${match.path}login`} component={Login}/>
<Route path={`${match.path}signup`} component={Signup}/>
</Switch>
</div>
</div>
)
}
}
render(){
return(
<div>
{this.isLoading()}
</div>
)
}
}
export default Out;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4855 次 |
最近记录: |