How to implement Role based restrictions/permissions in react redux app?

前端 未结 5 2126
醉梦人生
醉梦人生 2021-02-06 12:18

I have a React-Redux-KoaJs application with multiple components. I have few user roles as well. Now i want to display few buttons, tables and div to only specific roles and hide

5条回答
  •  执笔经年
    2021-02-06 12:49

    Be careful with that. If the actions of some roles are important you should always validate them at your backend. It's easy to change the values stored in redux at frontend allowing malicious use of the roles if there is no proper validation.

    If you want to proceed on a possible approach is this:

    • Save the roles at your reducer
    • Bind the reducer to the component:
    function mapStateToProps(state) {
      const { user_roles } = state;
      return { user_roles };
    }
    
    export default connect(mapStateToProps)(YourComponent);
    
    • Then at your component, you can check the user_roles and render the actions accordingly:
    render() {
        return (
          
    {this.props.user_roles.role === "YOUR_ROLE_TO_CHECK" && }
    ); }

    This will render the ActionsComponent only when the role is equal to the desired one.

    Again, always validate the roles at your backend!

提交回复
热议问题