🧸

【Flutter】google_sign_inのライブラリを使用して認証アカウントのidTokenを取得

2023/01/01に公開

概要

フロントエンド側で認証したGoogleの認証情報をバックエンドで使用する場合、以前に書いた記事Googleログイン認証のトークン検証の通り、idTokenを使用します。
今回はフロントエンド側でFlutterのGoogle認証ライブラリgoogle_sign_inを使用した場合、どのようにidTokenを取得するかのメモ書きです。

前提や参考等

サンプルソース

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

class GoogleAuthWidget extends StatelessWidget {
  const GoogleAuthWidget({super.key});

  
  Widget build(BuildContext context) {
    GoogleSignIn googleSignIn = GoogleSignIn(
      clientId: "GCPコンソールから取得したclientIdを設定",
      scopes: [
        'email',
        'https://www.googleapis.com/auth/contacts.readonly',
      ],
    );

    Future<void> getIdToken() async {
      try {
        var googleAuth = await googleSignIn.currentUser?.authentication;
        print(googleAuth!.idToken);
      } catch (error) {
        print("認証エラーが発生しました");
      }
    }

    googleSignIn.onCurrentUserChanged
        .listen((GoogleSignInAccount? account) async {
      await getIdToken();
    });

    Future<void> handleSignIn() async {
      try {
        if (googleSignIn.currentUser == null) {
          await googleSignIn.signIn();
        } else {
          // すでに認証済みの場合はidTokenを取得する
          await getIdToken();
        }
      } catch (error) {
        print("認証エラーが発生しました");
      }
    }

    return ElevatedButton(
      onPressed: handleSignIn,
      style: ElevatedButton.styleFrom(fixedSize: const Size(150, 50)),
      child: const Text('Google認証'),
    );
  }
}

Discussion