在 React 項目中使用 Auth0 并集成到后端服務(wù)的配置步驟詳解
在 React 項目中使用 Auth0 并集成到后端服務(wù)的配置步驟如下:
1. 在 Auth0 創(chuàng)建應(yīng)用程序
- 登錄到 Auth0 Dashboard.
- 導(dǎo)航到 “Applications” (應(yīng)用程序) 部分并點擊 “Create Application” (創(chuàng)建應(yīng)用程序).
- 為您的應(yīng)用程序命名并選擇應(yīng)用類型為 “Single Page Web Applications” (單頁 Web 應(yīng)用).
- 點擊 “Create” (創(chuàng)建).
2. 配置 Auth0 應(yīng)用程序
1.在應(yīng)用程序的設(shè)置頁面, 設(shè)置以下字段:
- Allowed Callback URLs: http://localhost:3000/callback (開發(fā)環(huán)境的本地地址)
- Allowed Logout URLs: http://localhost:3000 (開發(fā)環(huán)境的本地地址)
- Allowed Web Origins: http://localhost:3000 (開發(fā)環(huán)境的本地地址)
2.保存更改。
3. 在 React 項目中安裝 Auth0 SDK
在 React 項目根目錄下,打開終端并運行:
npm install @auth0/auth0-react
4. 在 React 項目中配置 Auth0
創(chuàng)建一個名為 auth_config.json
的文件,包含以下內(nèi)容:
{ "domain": "YOUR_AUTH0_DOMAIN", "clientId": "YOUR_AUTH0_CLIENT_ID", "audience": "YOUR_API_IDENTIFIER" }
在 src
目錄下創(chuàng)建一個名為 auth0-provider-with-history.js
的文件:
import React from "react"; import { useNavigate } from "react-router-dom"; import { Auth0Provider } from "@auth0/auth0-react"; import config from "./auth_config.json"; const Auth0ProviderWithHistory = ({ children }) => { const navigate = useNavigate(); const onRedirectCallback = (appState) => { navigate(appState?.returnTo || window.location.pathname); }; return ( <Auth0Provider domain={config.domain} clientId={config.clientId} audience={config.audience} redirectUri={window.location.origin} onRedirectCallback={onRedirectCallback} > {children} </Auth0Provider> ); }; export default Auth0ProviderWithHistory;
在 src/index.js
文件中使用 Auth0ProviderWithHistory
包裹應(yīng)用程序:
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import Auth0ProviderWithHistory from './auth0-provider-with-history'; import App from './App'; ReactDOM.render( <BrowserRouter> <Auth0ProviderWithHistory> <App /> </Auth0ProviderWithHistory> </BrowserRouter>, document.getElementById('root') );
5. 在 React 組件中使用 Auth0
使用 useAuth0
鉤子訪問 Auth0 認(rèn)證狀態(tài):
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const Profile = () => { const { user, isAuthenticated, isLoading } = useAuth0(); if (isLoading) { return <div>Loading...</div>; } return ( isAuthenticated && ( <div> <img src={user.picture} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> </div> ) ); }; export default Profile;
創(chuàng)建登錄和登出按鈕:
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; const LoginButton = () => { const { loginWithRedirect } = useAuth0(); return <button onClick={() => loginWithRedirect()}>Log In</button>; }; const LogoutButton = () => { const { logout } = useAuth0(); return <button onClick={() => logout({ returnTo: window.location.origin })}>Log Out</button>; }; export { LoginButton, LogoutButton };
6. 集成到后端服務(wù)
在后端服務(wù)中驗證 JWT 令牌。以 Go 為例,使用 github.com/auth0/go-jwt-middleware
和 github.com/form3tech-oss/jwt-go
:
package main import ( "net/http" "github.com/auth0/go-jwt-middleware" "github.com/dgrijalva/jwt-go" "github.com/gorilla/mux" ) var myJwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{ ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { audience := "YOUR_API_IDENTIFIER" checkAud := token.Claims.(jwt.MapClaims).VerifyAudience(audience, false) if !checkAud { return token, fmt.Errorf("invalid audience") } iss := "https://YOUR_AUTH0_DOMAIN/" checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false) if !checkIss { return token, fmt.Errorf("invalid issuer") } cert, err := getPemCert(token) if err != nil { return nil, err } return jwt.ParseRSAPublicKeyFromPEM([]byte(cert)) }, SigningMethod: jwt.SigningMethodRS256, }) func main() { r := mux.NewRouter() r.Handle("/api/private", myJwtMiddleware.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("This is a private endpoint")) }))) http.ListenAndServe(":8080", r) } func getPemCert(token *jwt.Token) (string, error) { // Implementation to get the PEM certificate }
在 React 項目中,使用 getAccessTokenSilently
方法獲取訪問令牌并將其添加到 API 請求的 Authorization
頭部:
import React from "react"; import { useAuth0 } from "@auth0/auth0-react"; import axios from "axios"; const CallApi = () => { const { getAccessTokenSilently } = useAuth0(); const callApi = async () => { try { const token = await getAccessTokenSilently(); const response = await axios.get("http://localhost:8080/api/private", { headers: { Authorization: `Bearer ${token}`, }, }); console.log(response.data); } catch (error) { console.error(error); } }; return <button onClick={callApi}>Call API</button>; }; export default CallApi;
通過以上步驟,您可以將 Auth0 集成到 React 項目并與后端服務(wù)交互。
到此這篇關(guān)于在 React 項目中使用 Auth0 并集成到后端服務(wù)的配置步驟的文章就介紹到這了,更多相關(guān)React 使用 Auth0 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React使用React.lazy和Suspense實現(xiàn)組件懶加載
React 提供了 React.lazy 和 Suspense 這兩個好東西,能讓我們實現(xiàn)組件的懶加載,下面就跟隨小編一起來了解一下如何使用它們實現(xiàn)懶加載的具體步驟吧2025-03-03一文詳解手動實現(xiàn)Recoil狀態(tài)管理基本原理
這篇文章主要為大家介紹了一文詳解手動實現(xiàn)Recoil狀態(tài)管理基本原理實例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05React組件創(chuàng)建與事件綁定的實現(xiàn)方法
react事件綁定時。this并不會指向當(dāng)前DOM元素。往往使用bind來改變this指向,今天通過本文給大家介紹React事件綁定的方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-12-12react?路由權(quán)限動態(tài)菜單方案配置react-router-auth-plus
這篇文章主要為大家介紹了react路由權(quán)限動態(tài)菜單方案react-router-auth-plus傻瓜式配置詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08react拖拽react-beautiful-dnd一維數(shù)組二維數(shù)組拖拽功能
二維數(shù)組可以拖拽,但是不可以編輯+拖拽,如果想要實現(xiàn)編輯+拖拽,還是需要轉(zhuǎn)換成一維數(shù)組,本文給大家介紹react拖拽react-beautiful-dnd的相關(guān)知識,感興趣的朋友跟隨小編一起看看吧2024-03-03