In React applications, obtaining routing authorization through the backend interface can achieve more dynamic and flexible permission management. The usual process is as follows:
- After the user logs in, obtain permission information:
After the user logs in successfully, obtain the user's permission information or accessible route list from the backend.
- Store permission information:
Store the obtained permission information in Redux, Context API, or local storage.
- Dynamically generate routes:
Dynamically generate routing configurations based on stored permission information.
- Create permission components:
Create a higher-order component (HOC) or custom hook (hook) to encapsulate permission logic.
The following is a detailed example that demonstrates how to obtain routing authorization through the backend interface and implement dynamic routing permission control in a React application.
1. Install the necessary libraries
npm install react-router-dom npm install redux react-redux npm install axios
2. Define backend interface calls and permission storage
// import axios from 'axios'; const api = ({ baseURL: '', }); export const login = async (username, password) => { const response = await ('/login', { username, password }); return ; }; export const getUserPermissions = async () => { const response = await ('/permissions'); return ; };
3. Create the Redux Store
// import { createStore } from 'redux'; const initialState = { auth: { isAuthenticated: false, permissions: [], }, }; const reducer = (state = initialState, action) => { switch () { case 'LOGIN': return { ...state, auth: { ..., isAuthenticated: true, permissions: , }, }; case 'LOGOUT': return { ...state, auth: { ..., isAuthenticated: false, permissions: [], }, }; default: return state; } }; const store = createStore(reducer); export default store;
4. User logs in and obtains permission information
// components/ 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 } }); ('/'); } catch (error) { ('Login failed', error); } }; return ( <div> <h1>Login</h1> <input type="text" value={username} onChange={(e) => setUsername()} placeholder="Username" /> <input type="password" value={password} onChange={(e) => setPassword()} placeholder="Password" /> <button onClick={handleLogin}>Login</button> </div> ); }; export default Login;
5. Dynamically generate routes
// 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) => ); 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 = ((route) => ((role) => (role)) ); return ( <Router> <Switch> {((route, index) => ( <PrivateRoute key={index} path={} component={} roles={} exact={} /> ))} <Route path="/login" component={Login} /> <Redirect to="/" /> </Switch> </Router> ); }; export default App;
6. Create permission components
// components/ 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) => ); return ( <Route {...rest} render={(props) => isAuthenticated && ((role) => (role)) ? ( <Component {...props} /> ) : ( <Redirect to="/login" /> ) } /> ); }; export default PrivateRoute;
Summarize
Through the above steps, we realize the acquisition of user permissions through the backend interface and dynamic routing permission control in the React application. This makes permission management more flexible and dynamic, and can dynamically generate and control routing based on different permissions of users. Depending on specific needs, permission logic can be further optimized and expanded.
This is the article about react's sample code to implement routing authorization through backend interface. For more related react routing authorization content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!