LoginSignup
45
33

More than 5 years have passed since last update.

Firebase Auth の refreshトークンの取得とIDトークンの更新

Last updated at Posted at 2019-01-15

概要

Firebase Auth については、以下のapps-gcpの記事か公式ドキュメントを参照でおk

・apps-gcp:面倒なログイン機能の実装はFirebase Authenticationに丸投げしよう
https://www.apps-gcp.com/firebase-authentication/
・Firebase Authentication 公式ドキュメント
https://firebase.google.com/docs/auth/?hl=ja

refreshトークンについて

そもそもFirebase Authに関しては、IDトークンが認証処理時に自動更新されるため、refreshを意識しなくてもいい。

しかし、それでもこっちからrefreshトークンを投げて、それによって更新されたIDトークンを返す、みたいな処理をやりたくなるときがあるのだ...

refreshトークン の取得

firebase.auth().onAuthStateChanged()などで取得する

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
    var refreshToken = user.refreshToken; //こんな感じ
    // ...
  } else {
    // User is signed out.
    // ...
  }
});

refreshトークンによるIDトークンの更新

以下のエンドポイントに先ほど取得したrefreshトークンをPOST。

https://securetoken.googleapis.com/v1/token?key=【API KEY】
ここでのAPI Keyは、
https://console.cloud.google.com/apis/credentials?hl=ja
で設定したキー。

Method: Post
Content-Type: application/x-www-form-urlencoded

Property Name Type Value
grant_type string "refresh_token"
refresh_token string 【上で取得したrefreshトークン】

ドキュメントはここ。ちとこのAPI古臭い
https://firebase.google.com/docs/reference/rest/auth/#section-refresh-token

POSTして成功したら、IDトークンが返ってくるので、それを使う。

以上。

45
33
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
45
33