React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > react 路由授权

react 通过后端接口实现路由授权的示例代码

作者:cangloe

本文主要介绍了React应用中通过后端接口获取路由授权,实现动态和灵活的权限管理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在 React 应用中,通过后端接口获取路由授权,可以实现更加动态和灵活的权限管理。通常流程如下:

用户登录成功后,从后端获取该用户的权限信息或可访问的路由列表。

将获取到的权限信息存储在 Redux、Context API 或 local storage 中。

根据存储的权限信息动态生成路由配置。

创建一个高阶组件(HOC)或自定义钩子(hook)来封装权限逻辑。
以下是一个详细的示例,演示如何通过后端接口获取路由授权并在 React 应用中实现动态路由权限控制。

1. 安装必要的库

npm install react-router-dom
npm install redux react-redux
npm install axios

2. 定义后端接口调用和权限存储

// api.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://your-api-base-url.com',
});

export const login = async (username, password) => {
  const response = await api.post('/login', { username, password });
  return response.data;
};

export const getUserPermissions = async () => {
  const response = await api.get('/permissions');
  return response.data;
};

3. 创建 Redux Store

// store.js
import { createStore } from 'redux';

const initialState = {
  auth: {
    isAuthenticated: false,
    permissions: [],
  },
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'LOGIN':
      return {
        ...state,
        auth: {
          ...state.auth,
          isAuthenticated: true,
          permissions: action.payload.permissions,
        },
      };
    case 'LOGOUT':
      return {
        ...state,
        auth: {
          ...state.auth,
          isAuthenticated: false,
          permissions: [],
        },
      };
    default:
      return state;
  }
};

const store = createStore(reducer);

export default store;

4. 用户登录并获取权限信息

// components/Login.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { login, getUserPermissions } from '../api';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const dispatch = useDispatch();
  const history = useHistory();

  const handleLogin = async () => {
    try {
      await login(username, password);
      const permissions = await getUserPermissions();
      dispatch({ type: 'LOGIN', payload: { permissions } });
      history.push('/');
    } catch (error) {
      console.error('Login failed', error);
    }
  };

  return (
    <div>
      <h1>Login</h1>
      <input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="Username"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;

5. 动态生成路由

// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';
import { useSelector } from 'react-redux';
import Home from './components/Home';
import Dashboard from './components/Dashboard';
import Profile from './components/Profile';
import Login from './components/Login';
import PrivateRoute from './components/PrivateRoute';

const App = () => {
  const permissions = useSelector((state) => state.auth.permissions);

  const routes = [
    { path: '/', component: Home, roles: ['user', 'admin'], exact: true },
    { path: '/dashboard', component: Dashboard, roles: ['admin'] },
    { path: '/profile', component: Profile, roles: ['user', 'admin'] },
    { path: '/login', component: Login, roles: [] },
  ];

  const filteredRoutes = routes.filter((route) =>
    route.roles.some((role) => permissions.includes(role))
  );

  return (
    <Router>
      <Switch>
        {filteredRoutes.map((route, index) => (
          <PrivateRoute
            key={index}
            path={route.path}
            component={route.component}
            roles={route.roles}
            exact={route.exact}
          />
        ))}
        <Route path="/login" component={Login} />
        <Redirect to="/" />
      </Switch>
    </Router>
  );
};

export default App;

6. 创建权限组件

// components/PrivateRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { useSelector } from 'react-redux';

const PrivateRoute = ({ component: Component, roles, ...rest }) => {
  const { isAuthenticated, permissions } = useSelector((state) => state.auth);

  return (
    <Route
      {...rest}
      render={(props) =>
        isAuthenticated && roles.some((role) => permissions.includes(role)) ? (
          <Component {...props} />
        ) : (
          <Redirect to="/login" />
        )
      }
    />
  );
};

export default PrivateRoute;

总结

通过上述步骤,我们实现了通过后端接口获取用户权限并在 React 应用中进行动态路由权限控制。这使得权限管理更加灵活和动态,能够根据用户的不同权限进行路由的动态生成和控制。根据具体需求,可以进一步优化和扩展权限逻辑。

到此这篇关于react 通过后端接口实现路由授权的示例代码的文章就介绍到这了,更多相关react 路由授权内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文