---
title: 'Google OAuth 2.0 to Access Google APIs'
disqus: hackmd
---
###### tags: `OAuth 2.0`
Google OAuth 2.0 to Access Google APIs
===
[TOC]
## 筆記目的
非常重要的筆記,可以說是使用Google API的觀念建立還有最重要的
讓你得到以下這些東西,並且可以不需要打程式碼,全部在Google的平台上面完成
1. clientID and clientSecret
2. access token
3. refresh token
具體請參考:
* [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/oauth2)
* [取得access token 一定要看](https://help.talend.com/r/Ovc10QFckCdvYbzxTECexA/qxe1u0OvHyl3sReqRafn1g)
* [stackoverflow的方法完整文字解釋](https://stackoverflow.com/questions/14948530/refresh-token-with-google-api-java-client-library)
* [官方方法](https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code)
* [csdn的方法](https://blog.csdn.net/lory17/article/details/54666920)
## 觀念的建立
要使用Google的各種服務,大致上都需要所謂的Oauth2 或是API金鑰(API key),這兩個都可以在GCP平台上完成,基本上若使用的是client library(電腦端)就只需要Oauth2不需要API key
另外要有個觀念GCP平台是幫你建立憑證,也就是你可以得到clientID還有clientsecret
,要透過另外一個平台OAuth 2.0 Playground,才能輕鬆地得到refresh token以及access token
這裡設定的細節在於
> Click Create credentials > OAuth client ID, and in the Create client ID page, create a new client ID TalendWebClient with Application type set to **Web application** and **Authorized redirect URIs** set to https://developers.google.com/oauthplayground.
> The created OAuth client ID and client secret will be used for obtaining the access token.
> Go to the Google Developers OAuth 2.0 Playground, click OAuth 2.0 Configuration and select Use your own OAuth credentials check box, enter the OAuth client ID and client secret you have already created in the OAuth Client ID and OAuth Client secret fields respectively.

> In OAuth 2.0 Playground Step 2, click Exchange authorization code for tokens to generate the OAuth access token
最後你會取得你想要的access token還有refresh token
把refresh token存起來,我們最後可以利用postman來取得每次的access token(因為只會存活3599秒)
請參考這篇筆記的[Make Api Call](https://hackmd.io/ILJcELGcQPq1tHJLzPioNw)
```
//post
https://oauth2.googleapis.com/token
```
大概會長這樣

## 整理重要步驟
1. 在GCP上取得clientID還有client secret
2. 在[Oauth2 playgroud](https://developers.google.com/oauthplayground/)平台中,透過clientID還有client secret取得refresh token
3. 在postman當中利用前面提到的網址,還有clientID,client secret還有refresh token來取得access token(因為這會一直變化,所以一定要重新取得,如果不想如此麻煩的話,建議都在client libray當中做完,那時只要把GCP上面的credention.json下載好就好了,詳情請去看drive api quickstart)
4. 利用access token還有API金鑰(可以在GCP平台上調用)調用dirve api服務