Cognito 사용자 풀에 등록된 사용자가 AWS Lambda API를 호출 할 때
Sign-in 을 통해 얻은 토큰으로 API를 호출 할 수 있도록 권한을 부여하는 방법과 API 호출 방법을 설명합니다.
0. API Gateway 에서 대상 API를 선택 한 후 -> 권한 부여자 -> 새로운 권한 생성을 클릭합니다.
1. 적당한 이름(여기서는 'CogAuth')을 입력하고 권한 부여자는 'Cognito'를 선택합니다.
2. 'Cognito 사용자 풀'에서 사용코자 하는 사용자 풀을 선택합니다.
3. '토큰 원본'에는 적당한 헤더 명을 입력합니다. 여기서는 'AuthTokenHeader' 라고 입력합니다.
4. '생성'을 클릭합니다.
5. API Gateway 에서 Lambda API가 연결된 메소드에 CORS 를 활성화 시킵니다.
6. 그리고 각 리소스의 메소드를 선택한 후 '메소드 요청'을 클릭합니다.
7. '승인'에서 연필아이콘을 클릭하여 'CogAuth'를 선택합니다.
상시 설정을 완료 하였다면, 아래의 코드를 실행해 봅니다.
import boto3
import json
from botocore.exceptions import ClientError
import httplib, urllib
host = 'blahblah123431244.execute-api.ap-region-2.amazonaws.com'
url = '/pr/test'
CLIENT_ID = "cognito_clientid"
#region을 지정하지 않으면 exception이 발생합니다
boto3.setup_default_session(region_name='ap-region-2')
client = boto3.client('cognito-idp', region_name='ap-region-2')
def callRestGet(tokenData):
headers = {
'User-Agent': 'python',
'Content-Type': 'application/json',
'AuthTokenHeader': tokenData
}
conn = httplib.HTTPSConnection(host)
conn.request("GET", url, headers=headers)
response = conn.getresponse()
data = response.read()
print(data)
def signin():
try:
response = cognito.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
AuthParameters={ 'USERNAME': 'mytempid', 'PASSWORD': '1234567' },
ClientMetadata={
'testval': '1234',
'testval2': '5678'
},
ClientId=CLIENT_ID)
callRestGet(response['AuthenticationResult']['IdToken'])
except ClientError as e:
print "Unexpected error: %s" % e즉, Sign-in 하여 'IdToken' 값을 얻은 후 API 호출시 헤더(AuthTokenHeader)값에 해당 토큰 값을 입력하고 호출 하는 예제입니다.
[참고] PYTHON에서 Cognito 에 Sign-up, Sign-in 하는 방법
- http://airpage.org/xe/language_data/26810