Google APIs with OAuth 2.0

random-developer·2022년 12월 2일
0

Google Cloud

목록 보기
2/4
post-thumbnail

Firestore REST API 사용 방법

파이어스토어에 접근하기 위해서는 Cloud Firestore API 를 유효화해야한다.
https://console.cloud.google.com/apis/api/firestore.googleapis.com

파이어스토어 API에 접근하는 방법은 두가지가 있다.
1. Firebase Authentication ID token
2. Google Identity OAuth 2.0 token

OAuth 2.0 token 을 취득하였다면 이를 Authorization 헤더 (Bearer) 에 넣어서 리퀘스트를 보낼 수 있게 된다.

예)

ACCESS_TOKEN=$(gcloud auth application-default print-access-token)

curl -v -H "Authorization: Bearer $ACCESS_TOKEN" https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/COLLECTION_NAME/DOCUMENT_ID

Google APIs 를 활용하기 위한 OAuth 2.0 플로우

https://developers.google.com/identity/protocols/oauth2 참고.

Web server application 시나리오, Installed application, Client-side (JavaScript) applications, Service account 시나리오가 있다.

플로우/시나리오에 따라 유저가 login & consent 를 했을 때 Access Token 이 바로 리턴되기도, Authorization code 가 리턴되기도 한다. Code 가 리턴되는 플로우를 사용하는 경우, Google Servers 에 리퀘스트를 한번 더 보내서 code 를 token 으로 바꿔야한다.

OAuth 2.0 token 취득 방법

확인이 필요하지만, 아래 모든 방법은 사전에 OAuth 2.o user consent 화면이 설정되어있어야 사용할수 있다.
APIs & Service 탭에서 OAuth 2.0 Client IDs 를 처음 만들 때, consent 화면 설정을 할 수 있다.

Internal 용과 External 용 두가지가 있는데, External 을 선택했을 경우, 테스트 환경이라면 Application Name 입력란에는 적단한 문자열을 넣으면 된다.

  1. gcloud 사용 gcloud auth application-default print-access-token
  2. Google Cloud Console & curl
  3. service account 와 Google API Client Library 를 사용
  4. service account 와 Using OAuth 2.0 for Server to Server Applications (HTTP/REST)

여기선 위 방법중 2. Google Cloud Console 을 사용해보면서, 토큰 취득까지의 시나리오를 경험해보도록 한다. 이 페이지가 공식문서이다. https://developers.google.com/identity/protocols/oauth2/web-serve

콘솔에서OAuth 2.0 Client IDs 생성을 클릭후 Application type 은 Web Applications 를 선택, Authorized redirect URIs 에는 적당히 'http://localhost' 나 'http://localhost:33333' 을 넣는다. 이제 CLIENT ID 와 CLIENT SECRET 이 생성된다. 파이어스토어의 경우, 토큰을 리퀘스트할때의 scope 은 'https://www.googleapis.com/auth/datastore' 으로 설정한다.

Desktop 에서 실행하는 경우엔 other 을 선택해도 상관없다. authorization flow 가 이 선택에 따라 달라지는데, web app 과 others는 기본적으로 똑같은 플로우다. 단, other 을 선택시 redirect URL 이 기본 설정치 urn:ietf:wg:oauth:2.0:oob 으로 설정되는데, 이후에 이 주소를 사용하면 된다.

아래 커맨드를 실행하여 출력된 URL 을 브라우저에서 실행하면, login & consent 화면이 뜬다. 각 API의 Scope 은, 이 페이지에서 확인 가능하다. access_type=offline 으로 설정하여 refresh token도 함께 취득 가능하도록 한다.

REDIRECT_ID=http://localhost
CLIENT_ID=xxx
SCOPE=https://www.googleapis.com/auth/datastore
echo "https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=${REDIRECT_URI}&client_id=${CLIENT_ID}&scope=${SCOPE}&response_type=code&access_type=offline"

인증이 완료되면 브라우저가 리다이렉트되는데, 리다이렉트된 URL을 확인해보면 Authorization code 가 있다. 이 코드와 CLIENT SECRET 사용해서 토큰을 요청한다.

CLIENT_SECRET=...
AUTHORIZATION_CODE='xxx'
curl -X POST \n
-d code=AUTHORIZATION_CODE \n
-d client_id=<クライアントID> \n
-d client_secret=<クライアントシークレット> \n
-d redirect_uri=<リダイレクトURI> \n
-d grant_type=authorization_code \n 
https://accounts.google.com/o/oauth2/token

리스폰스에는 ACCESS_TOKEN 뿐만 아니라, REFRESH_TOKEN 도 들어있다. Token 리스폰스에 포함된 scope 은 Authorization code 리퀘스트에서 보낸 scope 과 같지 않는 경우가 있으니 주의한다.

{
  "access_token": "...",
  "expires_in": 3599,
  "refresh_token": "...",
  "scope": "https://www.googleapis.com/auth/datastore",
  "token_type": "Bearer"
}

필요하다면 REFRESH_TOKEN 을 통해 새로운 ACCESS_TOKEN을 발급할 수도 있다.

REFRESH_TOKEN=...

curl --data "refresh_token=$REFRESH_TOKEN" --data "client_id=$CLIENT_ID" --data "client_secret=$CLIENT_SECRET" --data "grant_type=refresh_token" https://www.googleapis.com/oauth2/token

토큰이 무사히 리턴되었다면, 이제 이 토큰으로 Firestore API를 호출할 수 있다.

ACCESS_TOKEN=...
PROJECT_ID=...
COLLECTION_ID=...
DOCUMENT_ID=...
curl -H "Authorization: Bearer $ACCESS_TOKEN" https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/COLLECTION_ID/DOCUMENT_ID

물론, 실제로는 가장 간단한 방법은 gcloud 를 이용하는 방법이다.

gcloud auth application-default login

curl -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" https://firestore.googleapis.com/v1/projects/PROJECT_ID/databases/(default)/documents/COLLECTION_ID/DOCUMENT_ID

Access token 이나, refresh token을 무효화하려면 아래 API를 호출한다.

curl https://accounts.google.com/o/oauth2/revoke?token=ACCESS_TOKEN
curl https://accounts.google.com/o/oauth2/revoke?token=REFRESH_TOKEN

Access Token 의 상태(scope, expire)를 확인하려면, 아래 API를 호출한다.

curl "https://www.googleapis.com/oauth2/tokeninfo?access_token=$ACCESS_TOKEN"

(참고) Google APIs Explorer

구글 파이어스토어 API 페이지:
Google APIs Explorer 에서 Firestore 검색 후 Firestore API페이지를 클릭
Google APIs Explorer: https://developers.google.com/apis-explorer

profile
getRandomDeveloper()

0개의 댓글