LoginSignup
1
0

More than 3 years have passed since last update.

Vue.js から Google OAuthでaccess_token,refresh_tokenを取得する

Posted at

当ドキュメントが出来た理由

-フロントエンド:Vue.js
-バックエンド:Flask
の環境でアプリケーション構築を行っていた所、GoogleのOAuthの処理をバックエンド側から投げるとCORSエラーが出ます。CORSで検索すると色々な情報が出てくるのですが、最終的にそもそもそのような実装は出来ないという記載を見つけたため(どこだったか失念してしまったのですが)、今回はフロントエンドでOAuthをする実装を目指しました。
*もし同様の構成でバックエンドから投げても通る場合は教えて下さい
Vue.jsからGoogleのOAuthを行う方法を検索すると色々と出てくるのですが、最終的にrefresh_tokenが取得できずに数時間を溶かしたのでここに記しておきます。

vue.jsで使うライブラリはvue-google-oauth2

https://github.com/guruahn/vue-google-oauth2
こちらです。
インストール方法は記載の通りです。

main.js
Vue.use(GAuth, { 
  clientId: process.env.VUE_APP_GOOGLE_OAUTH_CLIENT_ID
  , scope: 'email profile openid https://www.googleapis.com/auth/calendar.readonly'
  , prompt: 'consent'
  , fetch_basic_profile: false
  }
)

こんな感じでVueに追加してください。

oauth.vue
        try {
          const authcode = await this.$gAuth.getAuthCode()
          if (!googleUser) {
            return null
          }else{
          this.$store
            .dispatch('getRefreshToken', {token: authcode})
            .then((data) => {
              this.loading = false
              //console.log('after getRefreshToken')
              //console.log(data)
            })
            .catch(() => {
              this.loading = false
            })
          }
        } catch (error) {
          console.error(error)
          return null
        }
      }

getAuthCode()でauthcodeが取得できます。
これを、バックエンドから投げることによって
access_token
refresh_token
token_expiry
を取得することが出来ます。

backend.py
@auth.route('/getRefreshToken', methods=['POST'])
def getRefreshToken():
    token = request.json.get("token", None)
    if token:
        try:
            credentials = client.credentials_from_code(os.environ.get("GOOGLE_OAUTH_CLIENT_ID"), os.environ.get("GOOGLE_OAUTH_CLIENT_SECRET"), scope='', code=token)
        except client.FlowExchangeError as e:
            print('outh error')
            print(e)
        else:
            return jsonify(access_token=credentials.access_token, refresh_token=credentials.refresh_token, token_expiry=credentials.token_expiry), 200
    else:
        return jsonify(google_token='false'), 200

コードはこちらを参照してます
https://github.com/guruahn/vue-google-oauth2/blob/master/backend-samples/python/main.py

credentialsの中に
access_token
refresh_token
token_expiry
の3つが入っていますので、それをよしなに使ってください。

refresh_tokenが取れなかった実装パターン

const googleUser = await this.$gAuth.getAuthCode()
これを
const googleUser = await this.$gAuth.signIn()
これで実装すると取得できませんでした。
特に必要としない場合はsignIn()で実装してしまえば、バックエンドから投げる必要が無いので簡単な実装ができます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0