Skip to content

Instantly share code, notes, and snippets.

@hugodias
Created July 26, 2020 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugodias/32d5b503c2bf2b23a41d18ff0a1d555e to your computer and use it in GitHub Desktop.
Save hugodias/32d5b503c2bf2b23a41d18ff0a1d555e to your computer and use it in GitHub Desktop.
Authorize Apollo with Auth0 Access Token Claims
import React from 'react'
import {
ApolloClient,
ApolloProvider,
InMemoryCache,
createHttpLink,
} from '@apollo/client'
import { setContext } from '@apollo/link-context'
import Loading from './components/Loading'
import { useAuth0 } from '@auth0/auth0-react'
import config from './auth_config.json'
export const AuthorizedApolloProvider = ({ children }) => {
const { loading, getAccessTokenSilently } = useAuth0()
if (loading) {
return <Loading />
}
const httpLink = createHttpLink({
uri: config.graphqlEndpoint, // your URI here...
})
const authLink = setContext(async () => {
const token = await getAccessTokenSilently()
console.log(token)
return {
headers: {
Authorization: `Bearer ${token}`,
},
}
})
const apolloClient = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
connectToDevTools: true,
})
return <ApolloProvider client={apolloClient}>{children}</ApolloProvider>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment