我有一個 React 應用程式,其中用戶物件作為 cookie 存盤在 App 組件中。這個用戶物件有一個AccountType整數屬性,1 表示用戶是學生,2 表示用戶是老師。
我正在使用 react-router v5 來保護某些路由不被訪問,除非登錄用戶是具有以下 RouteGuard 組件的 AccountType 2(教師):
const RouteGuard = ({ component: Component, ...rest }) => {
const user = JSON.parse(Cookies.get("loggedInUser"));
return (
<Route
{...rest}
render={(props) => {
return user.AccountType === 2 ? (
<Component />
) : (
<Redirect
to={{
pathname: "/403",
state: {
error: "You are not allowed to access this resource.",
from: props.location.pathname,
redirected: true,
},
}}
/>
);
}}
/>
);
};
以及如何使用此 RouteGuard 組件的示例:
<Switch>
<RouteGuard path="/records" exact component={Records} />
</Switch>
在正常情況下它運行良好,但我發現我可以以學生身份登錄并轉到開發者控制臺,在 cookie 部分,我可以修改 cookie 并手動將 AccountType 設定為 2,從而繞過路由保護。
防止未經授權的用戶篡改 cookie 并獲得對受保護端點的訪問權限的正確方法是什么?
uj5u.com熱心網友回復:
沒有辦法禁止這種情況。最好的方法是在本地存盤中存盤任何用戶名的版本,然后將該資料與服務器端資料庫進行比較,以確定該用戶是否具有所需的帳戶型別。
這是一個類似的問題: How to secure localStorage in HTML5?
uj5u.com熱心網友回復:
如果您從后端獲取此值并將其存盤在本地存盤中,它將解決您的問題。但是最好的方法是使用 JWT 令牌進行身份驗證并將必要的資訊傳遞給它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362810.html
標籤:javascript 反应 反应路由器
上一篇:承諾鏈中的重試功能
