发布于 2026-01-06 0 阅读
0

在 React-JS 中实现受保护的路由和身份验证非常有用,我之前一直被这个 bug 困扰,然后突然就看到了你的文章!DEV 的全球展示挑战赛由 Mux 呈现:展示你的项目!

在 React-JS 中实现受保护路由和身份验证

非常有用,我被这个bug困扰了好久,然后突然就看到了你的文章!

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

几乎所有网络应用程序都需要某种形式的身份验证,以防止未经授权的用户访问应用程序的内部运行机制。

在本教程中,我将展示如何设置身份验证路由,并保护其他路由不被未经授权的用户访问。

首先,

安装所有依赖项

  • npm i react-router react-router-dom
  • ./public/index.html在头部添加指向 Bootstrap CDN 的链接

React-router 将处理我们的路由,即在 Web 应用程序内从一个页面切换到另一个页面。

注意:我们将基于上一个项目“在 Web 应用中构建 Redux”进行构建。

家庭组件

首先,./src/view/Home我们创建一个 Home 组件作为首页。注意:在 onComponentDidMount 函数中,会获取一些演示数据https://jsonplaceholder.typicode.com/users来填充首页。
首页

登录组件

接下来./src/view/Authentication/Signin.js,我们来创建登录组件。
登录组件

OnInputChange 事件发生时,使用当前值更新 userData 状态;

 const handleInputChange = (e) => {
    setUserData((prevState) => {
      return {
        ...prevState,
        [e.target.name]: e.target.value,
      };
    });
  };
Enter fullscreen mode Exit fullscreen mode

OnSubmit,如果用户提供的username和分别与和匹配,passwordadmin123456

  • 保存isAuthenticatedtrue本地存储中,
  • 否则,显示相应的错误信息。保存在 localStorage 中的数据稍后将用于确认身份验证状态。
const handleSubmit = (e) => {
    e.preventDefault();

    //if username or password field is empty, return error message
    if (userData.username === "" || userData.password === "") {
      setErrorMessage((prevState) => ({
        value: "Empty username/password field",
      }));

    } else if (
      userData.username.toLowerCase() === "admin" &&
      userData.password === "123456"
    ) {
      //Signin Success
      localStorage.setItem("isAuthenticated", "true");
      window.location.pathname = "/";
    } else {
      //If credentials entered is invalid
      setErrorMessage((prevState) => ({ value: "Invalid username/password" }));
      return;
    }
  };
Enter fullscreen mode Exit fullscreen mode

App.js 组件

在 `<head>` 标签内./src/App.js,将创建的组件添加到 react-router-dom 的 BrowserRouter 中。

App.js

...

此时,如果项目启动,我们会跳转到登录页面,因为该path="/"路由指向组件。但是,最好保护该路由,使其仅对已认证用户开放,所有其他用户都被重定向到登录页面。这就引出了 React-JS 中的受保护路由 (Protected Route)Home的概念

受保护路线

受保护路由是指只有在满足特定条件(通常是用户通过身份验证)时才能访问的路由。它会返回一个对象,该Route对象会根据设定的条件渲染组件或将用户重定向到另一个路由。

./src/components/ProtectedRoute.js

  • 创建一个函数式组件,该组件接受组件和其他路由详细信息作为 props,然后
  • 检查条件以确认用户是否已通过身份验证。(在本例中,我们将从isAutheticated……获取localStorage
  • 如果值为真,则渲染组件;否则,Redirect跳转到/signin页面。
import React from "react";
import { Redirect, Route } from "react-router-dom";

function ProtectedRoute({ component: Component, ...restOfProps }) {
  const isAuthenticated = localStorage.getItem("isAuthenticated");
  console.log("this", isAuthenticated);

  return (
    <Route
      {...restOfProps}
      render={(props) =>
        isAuthenticated ? <Component {...props} /> : <Redirect to="/signin" />
      }
    />
  );
}

export default ProtectedRoute;

Enter fullscreen mode Exit fullscreen mode

./src/App.js在导入过程中,ProtectedRouteHome 组件传递给它。
受保护路线

让我们在首页添加注销按钮,点击注销按钮,清除isAuthenticatedlocalStorage 中的值,然后将路由重定向到登录页面。

替代文字

测试运行应用程序

应用程序启动后,将跳转到登录页面。
登入

要测试受保护的路由是否按预期工作,请编辑路由以访问主页http://localhost:3001/,您会注意到应用程序将重定向回登录页面http://localhost:3001/signin


使用以下凭据成功登录后,将显示登录页面:用户名: admin,密码:123456

着陆页

……这是GitHub
上的代码链接 希望对大家有所帮助。请点赞、分享和收藏。:) ……

如果您有兴趣实现用户几秒钟不活动后自动注销的功能,请阅读我写的下一篇文章——在 Web 应用程序中实现自动注销功能(React)。

文章来源:https://dev.to/olumidesamuel_/implementing-protected-route-and-authentication-in-react-js-3cl4