如何在 React 组件或 NextJs 应用程序中的“正常”函数中获取 Auth0 的 idToken?

问题描述 投票:0回答:1

我正在开发 NextJs 应用程序,我需要在每个后端调用中发送

idToken
。有一个简单的方法来实现吗?这是我们的应用程序结构(极其简化):

我们有一个页面:

/* src/pages/example/index.page.tsx */

export const getServerSideProps: GetServerSideProps<ExamplePageProps> = async (
  context,
) => {
  const initialTranslations = await getTranslations(context.locale, ['example']);
  return {
    props: {
      initialTranslations,
    },
  };
};

export interface ExamplePageProps {
  ...
}

function ExamplePage(props: ExamplePageProps) {
  return (
    <MyComponent />
  );
}

该组件如下所示:

/* src/pages/components/MyComponent/MyComponent.tsx */

export const MyComponent: FC<MyComponentProps> = (...) => {
  const handleClick = async () => {
    await makeBackendCall(param1, param2);
  }

  ...
  <Button onClick={handleClick} />
  ...
}

后端调用在这里:

/* src/fetchers/webapi.ts */

export const makeBackendCall = (param1: string, param2: string): Promise<Response> => {
  fetch('http://some.url', {
    method: 'GET',
    headers: {
      /* *** THIS IS WHERE I NEED TO SEND idToken *** */
    }
  });
}

export const anotherCallWhichNeedsTheToken = () => {...}
export const andAnotherOne = () => {...}
/*...*/

我怎样才能实现这个目标?到目前为止,我得到的最接近的是尝试通过以下方式在

getServerSideProps
中获取它:

import { getSession } from '@auth0/nextjs-auth0';
...
const session = getSession(context.req, context.res);
const idToken = session?.idToken;
...
return {
    props: {
      initialTranslations,
      idToken,
    },
};

...或更通用:

return {
  props: {
    initialTranslations,
    session: getSession(context.req, context.res),
  },
};

...但无论如何,我在

getServerSideProps
上遇到编译器错误,说一些关于 props 不兼容的事情(我认为这是关于在
getServerSideProps
中返回一个承诺并在组件 props 中指定一个“正常”对象,但我我不确定)。

next.js auth0
1个回答
0
投票

idToken 加密存储在 HttpOnly cookie 中,这就是您只能从后端代码读取它的原因。

如果您的获取请求针对与客户端位于同一域中的 API,则无需传递 idToken,因为 cookie 将在每个请求时自动传递到 API。您可以使用

getSession
函数从 API 读取它们。

如果您需要从另一个域获取数据,您可以在nextjs中创建一个代理API,并让代理API调用另一个域。这样你就不必从客户端传递 idToken,它可以是代理中的句柄。

© www.soinside.com 2019 - 2024. All rights reserved.