【问题标题】:Sending Amplify access token to server via Apollo Client通过 Apollo 客户端向服务器发送 Amplify 访问令牌
【发布时间】:2021-11-09 23:31:35
【问题描述】:

如何使用 Apollo 客户端将异步获取的 JWT 访问令牌从 AWS Amplify (Cognito) 发送到 Apollo 服务器以进行后端验证。

如果其他人需要它,就想办法。

为什么不使用 Appsync?截至 21 年 9 月 11 日,它还没有为我的用例实现足够的 GraphQL 规范。

【问题讨论】:

    标签: amazon-cognito apollo-client apollo-server amplify


    【解决方案1】:

    我正在使用 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(),
    })
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 1970-01-01
      • 2021-05-24
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2011-05-29
      • 1970-01-01
      相关资源
      最近更新 更多