[英]User Login and Roles in React or Node?
我正在構建一個使用完整 mern 堆棧的新應用程序,並且我堅持有關受保護路由、登錄/注冊和創建 ACL 用戶角色的最佳實踐。
我習慣於在節點中使用護照或 jwt 之類的東西來執行此操作,但是由於 react 擁有自己的路由器,我正在閱讀有一些方法可以在 react 本身中保護路由。 使用完整的 MERN 堆棧進行開發和設置用戶角色的最佳方式是什么?
謝謝
關於它的一些方法可能是 go
做第一個或第二個可以用類似的方式封裝
如果要根據權限顯示隱藏。
class CanUserView extends Component {
state = {allowed: false}
componentDidMount(){
this.checkPermissions()
}
async checkPermssions() {
//This is where the two strategies can differ.
//Either
Api.checkPermission(this.props.permission);
//Or
this.props.user.permissions.includes(permission)
}
render(){
if(this.state.allowed){
return this.props.children
} else {
return null;
}
}
}
然后你可以在你的代碼中使用它
<CanView permission={"Admin"}>
<AdminComponent />
</CanView>
當然,這不會對沒有權限的用戶隱藏代碼。 如果你想要那種用例,你可能需要在服務器端渲染並且只導入允許的 JS 文件。
我認為保護路由的最好方法是創建一個 ProtectedRoute 組件。
一個例子:(注意:你可以改變用戶是否登錄的邏輯,這里我以一個服務為例,你可以做任何你想做的事情,也許在localStorage中檢查一個令牌)
import React from "react";
import { Route, Redirect } from "react-router-dom";
import authService from "../../services/auth-service";
export const ProtectedRoute = ({
path,
component: Component,
auth,
render,
...rest
}) => {
return (
<Route
path={path}
{...rest}
render={props => {
if (authService.isAuthenticated()) {
return Component ? <Component {...props} /> : render(props);
} else {
return <Redirect to="/login" />;
}
}}
/>
);
};
在您的路由定義中,您可以使用此組件而不是 Route,如下所示:
<ProtectedRoute path="/protected-zone" exact component={YourProtectedComponent} />
擴展這個想法,你可以為不同的角色創建不同的 ProtectedRoute 組件。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.