3

我有一个使用 IAM 身份验证的 AppSync 应用程序(连接到 Cognito 用户和身份池)。使用 IAM 身份验证时,$event.context.identity 是一个 Cognito 身份池对象,没有用户信息(没有用户名、子、电子邮件等)

我相信每当我发出 graphQL 请求时,我都需要将 UserPoolID JWT(可通过 Amplify 在客户端使用)传递给 AppSync。但我一直无法弄清楚如何将 JWT 添加到(大概)标题中。
-------------EDIT------------- AppSyncClient 是客户端(基于 apollo 构建)。App.js 看起来像

import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import appSyncConfig from "./AppSync";
import { ApolloProvider } from "react-apollo";
import AWSAppSyncClient from "aws-appsync";
import { Rehydrated } from "aws-appsync-react";
import { Auth } from 'aws-amplify'
import AWS from'aws-sdk';

import AllPosts from './Components/AllPosts';
// more routes

const Home = () => (
  <div > <AllPosts /> </div>
);

const App = () => (
  <div> <Router> <div> 
        <Route exact={true} path="/" component={Home} /> 
        //more routes
   </div> </Router> </div>
);

const client = new AWSAppSyncClient({
  url: appSyncConfig.graphqlEndpoint,
  region: appSyncConfig.region,  
  auth: {
    type: appSyncConfig.authenticationType,  //AWS_IAM
    apiKey: appSyncConfig.apiKey,  
    credentials: () => Auth.currentCredentials(),
});

const WithProvider = () => (
  <ApolloProvider client={client}>
    <Rehydrated>
      <App />
    </Rehydrated>
  </ApolloProvider>
);

export default WithProvider;
4

1 回答 1

2

假设您的 GraphQL 客户端是 Apollo,关键是使用库setContext中的 authLink apollo-link-context

例子:

import ApolloClient from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { setContext } from 'apollo-link-context';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';
import { clientState } from './clientState';
import { Auth } from 'aws-amplify';

const cache = new InMemoryCache();

//TODO:  need to cache token
const authLink = setContext((request) => new Promise( (resolve, reject) => {
  Auth.currentSession()
  .then(session => {
    const token = session.idToken.jwtToken;
    resolve({
      headers: { Authorization: token }
    });
  })
}));

const stateLink = withClientState({ ...clientState, cache });

const client = new ApolloClient({
  cache,
  link: ApolloLink.from([
    authLink,
    stateLink, //near end but before HttpLink
    new HttpLink({uri: process.env.REACT_APP_GRAPHQL_ENDPOINT })
  ])
});

export default client;

(代码来自:https ://github.com/aws/aws-amplify/issues/434#issuecomment-372349010 )

于 2018-05-01T05:22:08.297 回答