gpt4 book ai didi

header - 使用 AWS Amplify 登录时,将 JWT 添加到所有 GraphQL/AppSynce 请求

转载 作者:行者123 更新时间:2023-12-04 16:02:29 26 4
gpt4 key购买 nike

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

我认为每当我发出 graphQL 请求时,我都需要将 UserPoolID JWT(可通过 Amplify 在客户端使用)传递给 AppSync。但我一直无法弄清楚如何将 JWT 添加到(大概) header 。
- - - - - - -编辑 - - - - - - - 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;

最佳答案

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

例子:

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)

关于header - 使用 AWS Amplify 登录时,将 JWT 添加到所有 GraphQL/AppSynce 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50111208/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com