본문 바로가기

리액트 네이티브

[인스타그램 클론코딩] 앱에서 백엔드로 Cognito 토큰 전송

1. ApolloClient 객체 생성

endpoint서버리스 GraphQL 백앤드 구축 포스트에서 배포할 때 얻은 API Gateway 주소를 입력해 주면 됩니다.

Amplify에서 주기적으로 토큰을 업데이트하기 때문에 GraphQL API 요청을 할 때마다 Auth 객체로 부터 토큰을 가져와야 합니다. 

ApolloClient 생성자의 request 속성은 [인스타그램 클론코딩] 웹에서 백엔드로 Cognito 토큰 전송 포스트에서와 마찬가지로 GraphQL API를 요청하기 전에 항상 거쳐가는 핸들러입니다.

reqeust로 전달되는 operation 객체를 사용해서 파라미터를 변경할 수 있습니다.

operation.setContext 메소드를 사용해서 토큰을 request.headers.authorization 속성에 입력해 줍니다.

App.js

import { Auth } from 'aws-amplify';

const client = new ApolloClient({
     cache: cache,
     uri: "<endpoint>",
     request: async operation => {
        const token = (await Auth.currentAuthenticatedUser()).signInUserSession.idToken.jwtToken;
        return operation.setContext({
           headers: { authorization: `${token}` }
        });
     },
});

2. Apollo 컨텍스트가 적용된 컴포넌트를 최상위 컴포넌트로 설정

App.js

ApolloProvider 컴포넌트는 [인스타그램 클론코딩] AuthContext 포스트에 설명한 컨텍스트 컴포넌트입니다.

이 컴포넌트에 client 속성에 1에서 만든 ApolloClient 객체를 입력해 줍니다.

return(
   <ApolloProvider client={client}>
     <NavController .../>
   </ApolloProvider>
)