我在 React 中使用以下插件(@axa-fr/react-oidc-context)来启用 AzureAd 身份验证。现在我需要在认证完成后访问 ApolloClient 中的 access_token。我不确定如何在 ApolloClient 等非反应组件中获取 access_token。
这就是我正在做的事情。
应用程序.js
import React from "react";
import { HashRouter, Route, Switch } from "react-router-dom";
import { AuthenticationProvider, withOidcSecure } from "@axa-fr/react-oidc-context";
import { IDENTITY_CONFIG } from "./utils/configuration";
// components
import Layout from "./Layout";
export default function App() {
return (
<AuthenticationProvider configuration={IDENTITY_CONFIG}>
<HashRouter>
<Switch>
<Route path="/" component={withOidcSecure(Layout)} />
</Switch>
</HashRouter>
</AuthenticationProvider>
);
}
布局.js
import React from "react";
import { Route, Switch, withRouter } from "react-router-dom";
import { ApolloProvider } from "@apollo/react-hooks";
import client from "./apollo";
import Dashboard from "./pages/dashboard";
function Layout(props) {
return (
<>
<ApolloProvider client={client}>
<Switch>
<Route exact path="/" component={Dashboard} />
</Switch>
</ApolloProvider>
</>
);
}
export default withRouter(Layout);
阿波罗.js
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloClient } from "apollo-client";
import { ApolloLink, split } from "apollo-link";
import { setContext } from "apollo-link-context";
import { HttpLink } from "apollo-link-http";
import { WebSocketLink } from "apollo-link-ws";
import { getMainDefinition } from "apollo-utilities";
import { useReactOidc } from "@axa-fr/react-oidc-context";
const { oidcUser } = useReactOidc();
console.log(oidcUser.access_token)
const httpUri = process.env.REACT_APP_SERVER_URL
? process.env.REACT_APP_SERVER_URL
: "https://48p1r2roz4.sse.codesandbox.io";
const wsUri = httpUri.replace(
/^https?/,
process.env.REACT_APP_ENV === "dev" ? "ws" : "wss"
);
const httpLink = new HttpLink({
uri: httpUri
});
const wsLink = new WebSocketLink({
uri: wsUri,
options: {
lazy: true,
reconnect: true
// connectionParams: () => {
// return { headers: { Authorization: getAuthHeader() } };
// }
}
});
const authLink = setContext((_, { headers }) => {
// const auth = getAuthHeader()
return {
headers: {
...headers
// Authorization: auth,
}
};
});
const terminatingLink = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === "OperationDefinition" && operation === "subscription";
},
wsLink,
authLink.concat(httpLink)
);
const link = ApolloLink.from([terminatingLink]);
const cache = new InMemoryCache();
const client = new ApolloClient({
link,
cache
});
export default client;
我正在尝试在 apollo.js 文件中提取访问令牌,但它会抛出错误,提示我无法访问非 React 组件中的 React Hooks。