自学内容网 自学内容网

在 React 项目中使用 Auth0 并集成到后端服务的配置步骤

在 React 项目中使用 Auth0 并集成到后端服务的配置步骤如下:

1. 在 Auth0 创建应用程序

  1. 登录到 Auth0 Dashboard.
  2. 导航到 “Applications” (应用程序) 部分并点击 “Create Application” (创建应用程序).
  3. 为您的应用程序命名并选择应用类型为 “Single Page Web Applications” (单页 Web 应用).
  4. 点击 “Create” (创建).

2. 配置 Auth0 应用程序

  1. 在应用程序的设置页面, 设置以下字段:
    • Allowed Callback URLs: http://localhost:3000/callback (开发环境的本地地址)
    • Allowed Logout URLs: http://localhost:3000 (开发环境的本地地址)
    • Allowed Web Origins: http://localhost:3000 (开发环境的本地地址)
  2. 保存更改。

3. 在 React 项目中安装 Auth0 SDK

在 React 项目根目录下,打开终端并运行:

npm install @auth0/auth0-react

4. 在 React 项目中配置 Auth0

  1. 创建一个名为 auth_config.json 的文件,包含以下内容:
{
  "domain": "YOUR_AUTH0_DOMAIN",
  "clientId": "YOUR_AUTH0_CLIENT_ID",
  "audience": "YOUR_API_IDENTIFIER"
}
  1. 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;
  1. 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

  1. 使用 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;
  1. 创建登录和登出按钮:
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. 集成到后端服务

  1. 在后端服务中验证 JWT 令牌。以 Go 为例,使用 github.com/auth0/go-jwt-middlewaregithub.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
}
  1. 在 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 项目并与后端服务交互。


原文地址:https://blog.csdn.net/Chloeeeeeeee/article/details/140177887

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!