auth0-react 是做什麼的?
在 React 應用程式中加入登入、登出、使用者工作階段及受保護路由等驗證功能時使用 - 整合 @auth0/auth0-react SDK,支援 Vite 或 Create React App 的單頁應用程式。
安裝
npm install @auth0/auth0-react
設定
在您的 Auth0 應用程式儀表板中,確保已設定好正確的允許回呼 URL、允許登出 URL 及允許的 Web 來源,例如:
http://localhost:5173(Vite 預設)http://localhost:3000(Create React App 預設)
使用方式
1. 使用 Auth0Provider 包裹應用程式
將 Auth0Provider 加入應用程式根元件,並傳入您的 Auth0 領域 (domain) 與用戶端 ID (clientId):
import React from 'react';
import { Auth0Provider } from '@auth0/auth0-react';
const App = () => {
return (
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
authorizationParams={{
redirect_uri: window.location.origin
}}
>
<MyApp />
</Auth0Provider>
);
};
2. 登入與登出
使用 useAuth0 hook 取得驗證狀態及方法:
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
const LoginButton = () => {
const { loginWithRedirect } = useAuth0();
return <button onClick={() => loginWithRedirect()}>登入</button>;
};
const LogoutButton = () => {
const { logout } = useAuth0();
return (
<button onClick={() => logout({ logoutParams: { returnTo: window.location.origin } })}>
登出
</button>
);
};
3. 存取使用者資訊
透過 user 物件取得使用者資料:
const { user, isAuthenticated } = useAuth0();
if (isAuthenticated) {
console.log(user); // 包含使用者資訊
}
4. 保護路由
建立一個 ProtectedRoute 元件來限制未驗證使用者的存取:
import React from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
const ProtectedRoute = ({ children }) => {
const { isAuthenticated, isLoading } = useAuth0();
if (isLoading) {
return <div>載入中...</div>;
}
return isAuthenticated ? children : <Navigate to="/login" />;
};
然後在路由中使用:
<Route path="/profile" element={<ProtectedRoute><Profile /></ProtectedRoute>} />