如何将 auth0 访问令牌添加到react-apollo

Raz*_*iti 7 apollo reactjs auth0 react-apollo apollo-client

我正在尝试在 React js 中向 apollo 客户端添加授权令牌以让用户登录...

\n

索引.js

\n
import React from 'react';\nimport ReactDOM from 'react-dom';\nimport { BrowserRouter as Router } from 'react-router-dom';\nimport { ThemeProvider } from 'react-jss';\nimport Theme from 'resources/theme';\nimport Routes from 'routes';\nimport './index.css';\nimport * as serviceWorker from './serviceWorker';\nimport { Auth0Provider } from "@auth0/auth0-react";\nimport 'bootstrap/dist/css/bootstrap.min.css';\nimport ReactNotification from 'react-notifications-component'\nimport './components/orders/fonts/NotoSansJP-Regular.otf'\nimport 'react-notifications-component/dist/theme.css'\nimport { ApolloProvider , ApolloClient, InMemoryCache } from '@apollo/client';\nimport { useAuth0 } from "@auth0/auth0-react";\n\n\nconst client = new ApolloClient({\nuri: process.env.REACT_APP_API_BACK ,\nheaders: {\n  Authorization: `Bearer ${accessToken}` // doesn\xe2\x80\x99t work \n },\n  cache: new InMemoryCache()\n});\n\n\nReactDOM.render(\n     <Auth0Provider\n    domain= {process.env.REACT_APP_AUTH0_DOMAIN }\n  clientId= {process.env.REACT_APP_AUTH0_CLIENT_ID}\n   redirectUri={window.location.origin}\n   audience={process.env.REACT_APP_AUTH0_AUDIENCE}\n   scope="warehouse"\n   \n  >\n    <ApolloProvider client={client}> \n    <ThemeProvider theme={Theme}>\n        <Router>\n        <ReactNotification />\n            <Routes />\n        </Router>\n    </ThemeProvider>,\n    </ApolloProvider>\n      </Auth0Provider>,\n    document.getElementById('root')\n);\n\nserviceWorker.unregister();\n
Run Code Online (Sandbox Code Playgroud)\n

要获取我需要导入的令牌:

\n
import { useAuth0 } from "@auth0/auth0-react";\n
Run Code Online (Sandbox Code Playgroud)\n

添加此行:

\n
const {  getAccessTokenSilently } = useAuth0();\n
Run Code Online (Sandbox Code Playgroud)\n

但这不能在index.js中完成我认为

\n

获取令牌:

\n
 const accessToken = await getAccessTokenSilently\n
Run Code Online (Sandbox Code Playgroud)\n

这是我在文档和谷歌搜索中找到的,但我认为在我的情况下无法完成,大多数教程都会展示如何在个人资料页面中获取用户数据(包括令牌),但这不是我想要的。

\n

我想将它传递给index.js中的客户端

\n

Rob*_*uch 10

这就是我最终所做的:

import {
  ApolloProvider,
  ApolloClient,
  InMemoryCache,
  HttpLink,
} from '@apollo/client';
import { setContext } from '@apollo/link-context';
import { useAuth0 } from '@auth0/auth0-react';

const ApolloProviderWithAuth0 = ({ children }) => {
  const { getAccessTokenSilently } = useAuth0();

  const httpLink = new HttpLink({
    uri: process.env.REACT_APP_GRAPHQL_URI,
  });

  const authLink = setContext(async (_, { headers, ...rest }) => {
    let token;
    try {
      token = await getAccessTokenSilently();
    } catch (error) {
      console.log(error);
    }

    if (!token) return { headers, ...rest };

    return {
      ...rest,
      headers: {
        ...headers,
        authorization: `Bearer ${token}`,
      },
    };
  });

  const client = React.useRef();

  if (!client.current) {
    client.current = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });
  }

  return (
    <ApolloProvider client={client.current}>
      {children}
    </ApolloProvider>
  );
};

export { ApolloProviderWithAuth0 };
Run Code Online (Sandbox Code Playgroud)

然后在您的 App 组件中将其用作 Provider。