OAuth2.0でrefresh_tokenを取得してGoogle APIにアクセス(access_tokenでAPIにアクセス)

技術備忘録

せっかくaccess_tokenを取得したものの、gapiへのセット方法がわからず時間をかけてしまったため、使用方法を記しておきます。結果的に、gapi.client.setToken()が実行できればAPIにアクセスできるようになることがわかりました。

スポンサーリンク

今回の内容

  • access_tokenを用いてアプリケーション上でAPIにアクセスできるようにする

refresh_token, access_tokenの取得方法は下記を参照

OAuth2.0でrefresh_tokenを取得してGoogle APIにアクセス(refresh_token, access_tokenの取得まで)

スポンサーリンク

全体の流れ

  • window.gapiでclient:auth2をロード
  • window.gapi.client.setToken({access_token: ‘xxxxxxxxxxxxxxxxxxxx’})でアクセストークンをセット
  • APIにアクセス
<script src="https://apis.google.com/js/api.js?onLoad=onGapiLoaded"></script>
const Config = {
    'clientId': process.env.REACT_APP_CLIENT_ID,
    'apiKey': process.env.REACT_APP_API_KEY,
    'scope': 'https://www.googleapis.com/auth/calendar',
    'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest']
}

class ApiCalendar{
    constructor(props) {
        this.access_token = props.access_token
        this.sign = false
        window.onGapiLoaded = this.handleClientLoad()
    }
    async handleClientLoad() {
        return await new Promise((resolve, reject) =>{
            window.gapi.load('client:auth2', () => {
                window.gapi.client.init(Config).then(() => {
                    window.gapi.client.setToken({access_token: this.access_token}) // access_tokenをセット
                    this.sign = true
                    resolve()
                },(error)=>{
                    alert(error['details'])
                })
            })
        })
    }
    getCalendarList() {
         return window.gapi.client.calendar.calendarList.list()
                .then(({result})=>{return result.items})
    }
}
スポンサーリンク

注意点

window.gapi.load('client:auth2', () => {
    window.gapi.client.init(Config).then(() => {

この部分はHTML上のスクリプトタグでapis.google.com/js/api.jsがロードされていないと実行することができません。そのため、ロードが完了するまで待つ必要があります。

scriptタグに ?onLoad=onGapiLoadedを設定し、

constructor内でwindow.onGapiLoaded = this.handleClientLoad()と設定することによって、gapiのロードが完了してからコードを実行することが出来ます。(この実行が完了されるまでgetCalendarList()は実行できません。)

参考ページ

Google OAuth2 – Using externally generated Access Token – With JS Client Library

コメント

タイトルとURLをコピーしました