首頁 > web前端 > js教程 > 主體

使用 Nanostores 和 Context API 在 React 應用程式中處理身份驗證

王林
發布: 2024-08-18 07:05:05
原創
965 人瀏覽過

HANDLING AUTH IN REACT APPS USING NANOSTORES AND CONTEXT API

在我開始使用 ReactJs 建立全端 Web 應用程式時,我發現自己對如何在前端處理身份驗證感到困惑。我的意思是,從後端收到訪問令牌後,您下一步該做什麼?如何保留登入狀態?

大多數初學者會認為「哦,只需將您的令牌儲存在狀態中即可」。但我很快就發現這不是最好的解決方案,甚至根本不是一個解決方案,因為正如大多數經驗豐富的ReactJs 開發人員所知,狀態是暫時的,因為每次刷新頁面時它都會被清除,我們絕對可以'用戶每次刷新都不需要登入。

快進到現在,我已經獲得了一些在React 中構建全棧應用程序的經驗,研究了更有經驗的開發人員的身份驗證方法並在其他兩個應用程序中復制了該過程,我想提供一個指導關於我目前如何處理它。有些人可能認為這不是最好的方法,但我現在已經採用它作為我的方法,我願意學習其他開發人員使用的其他方法。

第一步

您已將電子郵件和密碼(假設您使用基本電子郵件和密碼身份驗證)提交到後端以啟動身份驗證程序。我不會談論後端如何處理身份驗證,因為本文是關於如何僅在前端處理身份驗證。我將跳到您在 HTTP 回應中收到令牌的部分。以下是一個簡單登入表單元件的程式碼範例,該元件將電子郵件和密碼提交到伺服器並在回應中接收令牌和使用者資訊。現在為了簡單起見,我的表單值是透過狀態來管理的,對於生產應用程式來說,使用像 formik 這樣強大的程式庫會更好。

import axios from 'axios'
import { useState } from "react"

export default function LoginForm() {
    const [email, setEmail] = useState("")
    const [password, setPassword] = useState("")

    const handleSubmit = async() => {
        try {
            const response = await axios.post("/api/auth/login", { email, password })
            if (response?.status !== 200) {
                throw new Error("Failed login")
            }
            const token = response?.data?.token
            const userInfo = response?.data?.userInfo
        } catch (error) {
            throw error
        }
    }

    return(
        <form onSubmit={handleSubmit}>
            <div>
                <input name="email" onChange={(e) => setEmail(e.target.value)}/>
                <input name="password" onChange={(e) => setPassword(e.target.value)}/>
            </div>
            <div>
                <button type="submit">
                    Login
                </button>
            </div>
        </form>
    )
}
登入後複製

第二步

包裝整個應用程序,或僅包裝需要存取身份驗證上下文提供者中的身份驗證狀態的部分。這通常在根 App.jsx 檔案中完成。如果您不知道 context API 是什麼,請隨時查看 Reactjs 文件。下面的範例顯示了已建立的 AuthContext 提供者元件。然後將其導入到 App.jsx 中,並用於包裝 App 元件中傳回的 RouterProvider,從而使身份驗證狀態可以從應用程式中的任何位置存取。

import { createContext } from "react";

export const AuthContext = createContext(null)

export default function AuthProvider({children}) {

    return(
        <AuthContext.Provider>
            {children}
        </AuthContext.Provider>
    )
}
登入後複製
import React from "react";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import AuthProvider from "./AuthContext";

const router = createBrowserRouter([
    // your routes here
])

function App() {
    return(
        <AuthProvider>
            <RouterProvider router={router} />
        </AuthProvider>
    )
}

export default App
登入後複製

第三步

在驗證上下文中,您必須初始化兩個狀態變數「isLoggedIn」和「authenticatedUser」。第一個狀態是布林類型,最初設定為“false”,然後在確認登入後更新為“true”。第二個狀態變數用於儲存登入使用者的信息,例如姓名、電子郵件等。這些狀態變數必須包含在上下文元件中傳回的提供者的值中,以便可以在整個應用程式中存取它們以進行條件渲染.

import { createContext, useState } from "react";

export const AuthContext = createContext(null)

export default function AuthProvider({children}) {
    const [isLoggedIn, setIsLoggedIn] = useState(false)
    const [authenticatedUser, setAuthenticatedUser] = useState(null)

    const values = {
        isLoggedIn,
        authenticatedUser,
        setAuthenticatedUser
    }

    return(
        <AuthContext.Provider value={values}>
            {children}
        </AuthContext.Provider>
    )
}
登入後複製

第四步

Nanostores 是一個用於管理 Javascript 應用程式狀態的套件。該套件提供了一個簡單的 API,用於管理跨多個元件的狀態值,只需在單獨的文件中初始化它並將其導入到您想要使用狀態或更新狀態的任何元件中即可。但是,為了儲存在第一步驟中的 HTTP 回應中收到的驗證令牌,您將使用 nanostores/persistent。該套件透過將狀態儲存在 localStorage 中來保留您的狀態,這樣當您刷新頁面時它就不會被清除。 @nanostores/react 是針對 Nanostore 的 React 特定集成,它使 useStore 鉤子可用於從 Nanostore 狀態中提取值。

所以現在你可以繼續:

  • 安裝以下軟體包:nanostores、@nanostores/persistent 和 @nanostores/react。

  • 在名為 user.atom.js 或您選擇的任何名稱的單獨檔案中,使用 nanostores/persistent 初始化「authToken」儲存和「user」儲存。

  • 將它們匯入到您的登入表單元件檔案中,並使用登入回應中收到的令牌和使用者資料更新狀態。

npm i nanostores @nanostores/persistent @nanostores/react
登入後複製
import { persistentMap } from '@nanostores/persistent'

export const authToken = persistentMap('token', null)

export const user = persistentMap('user', null)
登入後複製
import { authToken, user } from './user.atom'

 const handleSubmit = async() => {
        try {
            const response = await axios.post("/api/auth/login", { email, password })
            if (response?.status !== 200) {
                throw new Error("Failed login")
            }
            const token = response?.data?.token
            const userInfo = response?.data?.userInfo

            authToken.set(token)
            user.set(userInfo)
        } catch (error) {
            throw error
        }
    }
登入後複製

第五步

現在,在包裝應用程式的身份驗證上下文中,您必須確保令牌和使用者狀態保持更新並在整個應用程式中可用。要實現這一目標,您必須:

  • 匯入‘authToken’和‘user’儲存。

  • Initialie a useEffect hook, inside of the hook, create a ‘checkLogin()’ function which will check whether the token is present in the ‘authToken’ store, if it is, run a function to check whether it’s expired. Based on your results from checking, you either redirect the user to the login page to get authenticated OR… set the ‘isLoggedIn’ state to true. Now to make sure the login state is tracked more frequently, this hook can be set to run every time the current path changes, this way, a user can get kicked out or redirected to the login page if their token expires while interacting with the app.

  • Initialize another useEffect hook which will contain a function for fetching the user information from the backend using the token in the authToken store every time the app is loaded or refreshed. If you receive a successful response, set the ‘isLoggedIn’ state to true and update the ‘authenticatedUser’ state and the ‘user’ store with the user info received in the response.

Below is the updated AuthProvider component file.

import { createContext, useState } from "react";
import { authToken, user } from './user.atom';
import { useStore } from "@nanostores/react";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";

export const AuthContext = createContext(null)

export default function AuthProvider({children}) {
    const [isLoggedIn, setIsLoggedIn] = useState(false)
    const [authenticatedUser, setAuthenticatedUser] = useState(null)
    const token = useStore(authToken)
    const navigate = useNavigate()
    const { pathname } = useLocation()

    function isTokenExpired() {
        // verify token expiration and return true or false
    }

    // Hook to check if user is logged in 
    useEffect(() => {
        async function checkLogin () {
            if (token) {

              const expiredToken = isTokenExpired(token);

              if (expiredToken) {
                // clear out expired token and user from store and navigate to login page
                authToken.set(null)
                user.set(null)
                setIsLoggedIn(false);
                navigate("/login");
                return;
              }
            }
        };

        checkLogin()
    }, [pathname])

    // Hook to fetch current user info and update state
    useEffect(() => {
        async function fetchUser() {
            const response = await axios.get("/api/auth/user", {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })

            if(response?.status !== 200) {
                throw new Error("Failed to fetch user data")
            }

            setAuthenticatedUser(response?.data)
            setIsLoggedIn(true)
        }

        fetchUser()
    }, [])

    const values = {
        isLoggedIn,
        authenticatedUser,
        setAuthenticatedUser
    }

    return(
        <AuthContext.Provider value={values}>
            {children}
        </AuthContext.Provider>
    )
}

登入後複製

CONCLUSION

Now these two useEffect hooks created in step five are responsible for keeping your entire app’s auth state managed. Every time you do a refresh, they run to check your token in local storage, retrieve the most current user data straight from the backend and update your ‘isLoggedIn’ and ‘authenticatedUser’ state. You can use the states within any component by importing the ‘AuthContext’ and the ‘useContext’ hook from react and calling them within your component to access the values and use them for some conditional rendering.

import { useContext } from "react";
import { AuthContext } from "./AuthContext";

export default function MyLoggedInComponent() {

    const { isLoggedIn, authenticatedUser } = useContext(AuthContext)

    return(
        <>
        {
            isLoggedIn ? 
            <p>Welcome {authenticatedUser?.name}</p>
            :
            <button>Login</button>
        }
        </>
    )
}
登入後複製

Remember on logout, you have to clear the ‘authToken’ and ‘user’ store by setting them to null. You also need to set ‘isLoggedIn’ to false and ‘authenticatedUser’ to null.

Thanks for reading!

以上是使用 Nanostores 和 Context API 在 React 應用程式中處理身份驗證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!