如何使用Apollo Client将异步获取的JWT访问令牌从AWS Amplify (Cognito)发送到Apollo服务器以进行后端验证。
如果其他人需要它的话我就知道了。
为什么不使用Appsync?从9/11/21开始,它还没有为我的用例实现足够的GraphQL规范。
发布于 2021-11-09 07:25:16
我正在使用React-native expo,并使用react-native-dotenv加载我的graphql端点url。
import {
ApolloClient, ApolloLink, HttpLink, InMemoryCache
} from "@apollo/client"
import { setContext } from '@apollo/client/link/context'
import Auth from "@aws-amplify/auth"
import { ENDPOINT } from "@env"
if (!ENDPOINT) {
throw new Error("Need env ENDPOINT")
}
const httpLink = new HttpLink({ uri: GRAPHQL_ENDPOINT })
const authMiddleware = setContext(async (_, { headers }) => {
try {
const currentSession = await Auth.currentSession()
const accessToken = currentSession.getAccessToken()
const token = accessToken.getJwtToken()
return {
headers: {
...headers,
authorization: token || null,
},
}
} catch (err) {
return {
headers,
}
}
})
const link = ApolloLink.from([
authMiddleware,
httpLink
])
export const apolloClient = new ApolloClient({
link,
cache: new InMemoryCache(),
})
https://stackoverflow.com/questions/69900718
复制