【问题标题】:How to get Auth0 token from outside React components?如何从外部 React 组件获取 Auth0 令牌?
【发布时间】:2022-03-21 21:53:57
【问题描述】:

我正在使用 axios 向我的 API 发出请求。目前我使用 axios 拦截器为每个发送的请求设置令牌(因此我不必重复从组件内获取令牌)。有没有办法做到这一点?我的第一次尝试看起来像这样:

// axios.ts
import { useAuth0 } from "@auth0/auth0-react";
import axios from "axios";

const fetchClient = axios.create();

fetchClient.interceptors.request.use(
  async (config) => {
    const { user, getAccessTokenSilently } = useAuth0();

    if (!user || !user.sub) return Promise.reject("No user");

    const token = await getAccessTokenSilently({
      audience: process.env.REACT_APP_AUTH0_API_AUDIENCE,
    });

    const userId = user.sub.split("|")[1];
    config.headers["Authorization"] = `Bearer ${token}`;
    config.headers["userId"] = userId;
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

export default fetchClient;

当然你不能调用 Hooks,因此不能从非功能组件调用getAccessTokenSilently。有什么办法可以解决这个问题?谢谢大家

【问题讨论】:

标签: reactjs axios auth0


【解决方案1】:

我通过将getAccessTokenSilently 作为参数传递给我的 axios 文件中的函数来解决了这个问题。


import axios from "axios";

const httpClient = axios.create();

// adds access tokens in all api requests
// this interceptor is only added when the auth0 instance is ready and exports the getAccessTokenSilently method
export const addAccessTokenInterceptor = (getAccessTokenSilently) => {
  httpClient.interceptors.request.use(async (config) => {
    const token = await getAccessTokenSilently();
    config.headers.Authorization = `Bearer ${token}`;
    return config;
  });
};

export default httpClient;

然后在我的 App.jsx 中,一旦 Auth0 实例准备好,我就使用了一个 useEffect 来执行这个函数:


import { useEffect } from "react";
import { useAuth0 } from "@auth0/auth0-react";
import { addAccessTokenInterceptor } from "./api/httpClient";

const App = () => {

  const { getAccessTokenSilently } = useAuth0();

  useEffect(() => {
    addAccessTokenInterceptor(getAccessTokenSilently);
  }, [getAccessTokenSilently]);

   return (
    <div>
      Your app here...
    </div>
  );
}

export default App;

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2019-11-08
    相关资源
    最近更新 更多