在 React 项目中使用 Auth0 并集成到后端服务的配置步骤如下:
1. 在 Auth0 创建应用程序
- 登录到 Auth0 Dashboard.
- 导航到 “Applications” (应用程序) 部分并点击 “Create Application” (创建应用程序).
- 为您的应用程序命名并选择应用类型为 “Single Page Web Applications” (单页 Web 应用).
- 点击 “Create” (创建).
2. 配置 Auth0 应用程序
- 在应用程序的设置页面, 设置以下字段:
- Allowed Callback URLs:
http://localhost:3000/callback
(开发环境的本地地址) - Allowed Logout URLs:
http://localhost:3000
(开发环境的本地地址) - Allowed Web Origins:
http://localhost:3000
(开发环境的本地地址)
- Allowed Callback URLs:
- 保存更改。
3. 在 React 项目中安装 Auth0 SDK
在 React 项目根目录下,打开终端并运行:
npm install @auth0/auth0-react
4. 在 React 项目中配置 Auth0
- 创建一个名为
auth_config.json
的文件,包含以下内容:
{
"domain": "YOUR_AUTH0_DOMAIN",
"clientId": "YOUR_AUTH0_CLIENT_ID",
"audience": "YOUR_API_IDENTIFIER"
}
- 在
src
目录下创建一个名为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
包裹应用程序:
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 认证状态:
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;
- 创建登录和登出按钮:
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. 集成到后端服务
- 在后端服务中验证 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 项目并与后端服务交互。