Sco*_*ott 1 authentication jwt react-router
我希望为React Router
应用程序实现真实世界的身份验证。我见过的每个教程都fakeAuth
用于模拟身份验证,但实际上并没有实现真实世界的身份验证。我正在尝试实际实施身份验证。这可能吗?
现在,我发送jwt
给后端,以检查它是否在返回之前有效Component
我想渲染-Redirect
到Login
如果jwt
认证失败,或者render
Dashboard
如果它是有效的jwt
。问题是ProtectedRoute
是return
荷兰国际集团的redirect
到/login
后端之前return
荷兰国际集团是否jwt
是有效还是无效。
如何在我的React-Router
应用程序中获得真实世界的身份验证?这甚至可能吗?
const PrivateRoute = ({ component: Component, ...rest }) => {
const [auth, setAuth] = useState(false);
useEffect(() => {}, [auth])
useEffect(() => {
// send jwt to API to see if it's valid
let token = localStorage.getItem("token");
if (token) {
fetch("/protected", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ token })
})
.then((res) => {
return res.json()
})
.then((json) => {
if (json.success) {
setAuth(true);
}
})
.catch((err) => {
setAuth(false);
localStorage.removeItem("token");
});
}
}, [])
return (<Route {...rest}
render={(props) => {
return auth ? <Component {...props} /> : <Redirect to="/login" />
}} />)
}
}
Run Code Online (Sandbox Code Playgroud)
我会说你需要一个在认证/无效 jwt 之间的状态。我会使用另一个状态字段,isTokenValidated(或 isLoading):
const PrivateRoute = ({ component: Component, ...rest }) => {
const [auth, setAuth] = useState(false);
const [isTokenValidated, setIsTokenValidated] = useState(false);
useEffect(() => {
// send jwt to API to see if it's valid
let token = localStorage.getItem("token");
if (token) {
fetch("/protected", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ token })
})
.then((res) => {
return res.json()
})
.then((json) => {
if (json.success) {
setAuth(true);
}
})
.catch((err) => {
setAuth(false);
localStorage.removeItem("token");
})
.then(() => setIsTokenValidated(true));
} else {
setIsTokenValidated(true); // in case there is no token
}
}, [])
if (!isTokenValidated) return <div />; // or some kind of loading animation
return (<Route {...rest}
render={(props) => {
return auth ? <Component {...props} /> : <Redirect to="/login" />
}} />)
}
}
Run Code Online (Sandbox Code Playgroud)